agentix-cli 0.103.2 → 0.104.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.
@@ -7,8 +7,9 @@ import AppKit
7
7
  /// The answering agent can send it to something on screen, which it
8
8
  /// marks (#482). Chosen with `voice.look`; the orb stays the default.
9
9
  ///
10
- /// It reacts and never interrupts: its window takes no keys, no clicks
11
- /// but a drag of its body with ⌘ held, and never comes forward by itself.
10
+ /// It reacts and never interrupts: its window takes no keys and never
11
+ /// comes forward by itself. It takes a drag of its body with ⌘ held, and
12
+ /// idle with no bubble a click and a right-click on its body (#579).
12
13
  /// With Reduce Motion on, or "Animated orb" off in the menu, it is a
13
14
  /// still picture that changes between states and stays where it rests.
14
15
  @MainActor
@@ -72,6 +73,15 @@ final class CharacterHost {
72
73
  /// Carried by the pointer: where the pointer took hold, and where it
73
74
  /// stood then, which is not where it rests once it has stepped aside.
74
75
  private var carried: (from: NSPoint, rest: CGPoint)?
76
+ /// Idle with no bubble, a click on it talks and a right-click opens
77
+ /// the menu, as on the pill (#579). Set by the app.
78
+ var onClick: (() -> Void)?
79
+ var contextMenu: (() -> NSMenu)?
80
+ private var clickable: Bool {
81
+ CharacterMath.clickable(activity, asked: asked, sent: guide.showing != nil, bubble: bubbleFrame != nil)
82
+ }
83
+ /// The press that carries it began as a click.
84
+ private var pressed = false
75
85
  /// What the answering agent sent it to show (#482), and its mark.
76
86
  private let guide = CharacterGuide()
77
87
  /// Sent somewhere, and what its bubble says there (#562).
@@ -102,6 +112,10 @@ final class CharacterHost {
102
112
  window.ignoresMouseEvents = true
103
113
  window.contentView = view
104
114
  view.onDrag = { [weak self] phase in self?.drag(phase) }
115
+ view.onMenu = { [weak self] event in
116
+ guard let self, let menu = self.contextMenu?() else { return }
117
+ NSMenu.popUpContextMenu(menu, with: event, for: self.view)
118
+ }
105
119
  view.unit = Self.diameter / 100
106
120
  view.edge = CGPoint(x: Self.size.width / 2, y: Self.size.height - Self.ground)
107
121
  motionObserver = NSWorkspace.shared.notificationCenter.addObserver(
@@ -206,12 +220,13 @@ final class CharacterHost {
206
220
  self.timer = timer
207
221
  }
208
222
 
209
- /// It takes the pointer only to be moved: on its body, with ⌘ held.
210
- /// Any other click goes through it to the window behind.
223
+ /// It takes the pointer on its body: with ⌘ held to be moved, and
224
+ /// idle with no bubble to be clicked. Any other click goes through it
225
+ /// to the window behind.
211
226
  private func aim() {
212
227
  // The button came up where no event told of it.
213
228
  if carried != nil && NSEvent.pressedMouseButtons & 1 == 0 { drop() }
214
- let take = carried != nil || (NSEvent.modifierFlags.contains(.command) && body.contains(pointerSource()))
229
+ let take = carried != nil || ((clickable || NSEvent.modifierFlags.contains(.command)) && body.contains(pointerSource()))
215
230
  if window.ignoresMouseEvents == take { window.ignoresMouseEvents = !take }
216
231
  }
217
232
 
@@ -219,20 +234,26 @@ final class CharacterHost {
219
234
  switch phase {
220
235
  case .began:
221
236
  let mouse = pointerSource()
237
+ pressed = clickable
222
238
  if body.contains(mouse) { guide.end(glide: false); onGuide?(); carried = (mouse, CGPoint(x: body.midX, y: rest.y)) }
223
239
  case .moved:
224
240
  if carried != nil { tick() }
225
241
  case .ended:
226
242
  if carried != nil { tick() }
227
- drop()
243
+ drop(click: pressed)
228
244
  }
229
245
  }
230
246
 
231
- /// Let go: where it was carried to is kept. A click alone moves nothing.
232
- private func drop() {
247
+ /// Let go: where it was carried to is kept. A click alone moves
248
+ /// nothing; on a character that could be clicked, it talks.
249
+ private func drop(click: Bool = false) {
233
250
  guard let was = carried else { return }
234
251
  carried = nil
235
- guard pointerSource() != was.from else { return }
252
+ let now = pointerSource()
253
+ guard hypot(now.x - was.from.x, now.y - was.from.y) >= 4 else {
254
+ if click { onClick?() }
255
+ return
256
+ }
236
257
  place = rest
237
258
  Config.characterPlace = rest
238
259
  }
@@ -287,7 +308,7 @@ final class CharacterHost {
287
308
  edges = strolls && Config.playMode ? Meets.edges(of: Meets.windows(), band: (top - Self.head)...top) : []
288
309
  }
289
310
  frame = sim.step(to: now,
290
- CharacterSim.Input(activity: activity, level: level, pointer: pointer, held: held, sent: guide.showing != nil, asked: asked, strolls: strolls,
311
+ CharacterSim.Input(activity: activity, level: level, pointer: pointer, held: held, clickable: clickable, sent: guide.showing != nil, asked: asked, strolls: strolls,
291
312
  edges: edges, shows: bubbleShows?() ?? false, plays: Config.playMode, animates: quiet ? 0 : animates, down: NSEvent.pressedMouseButtons & 1 != 0,
292
313
  home: home, range: Double(spot.ends.lowerBound)...Double(spot.ends.upperBound)))
293
314
  }
@@ -44,6 +44,12 @@ enum CharacterMath {
44
44
  }
45
45
  }
46
46
 
47
+ /// It can be clicked (#579): idle, where it rests, with no bubble to
48
+ /// click in its place. Then it waits for the pointer and takes the click.
49
+ static func clickable(_ activity: Activity, asked: Mood?, sent: Bool, bubble: Bool) -> Bool {
50
+ activity == .idle && asked == nil && !sent && !bubble
51
+ }
52
+
47
53
  /// The state it goes through on the way from `from` to `to`, if any:
48
54
  /// it notices you before it listens and when it wakes, and nods once
49
55
  /// it has heard you.
@@ -78,10 +78,11 @@ struct CharacterSim {
78
78
  // The pointer comes close: out of its way. Left alone: back home,
79
79
  // unless the pointer is resting there.
80
80
  let near = input.pointer.map { abs($0.x - x) < reach && abs($0.y) < tall } ?? false
81
+ let held = input.held || (input.clickable && near)
81
82
  // Idle with play mode on, a game with the pointer comes first.
82
83
  // Sent to show something, it does not play.
83
84
  var game = PointerPlay.Out()
84
- if input.plays && !input.sent && !input.held && !input.shows && mood == .idle && input.activity == .idle {
85
+ if input.plays && !input.sent && !held && !input.shows && mood == .idle && input.activity == .idle {
85
86
  game = play.step(now, dt, x: x, pointer: input.pointer, down: input.down, range: input.range)
86
87
  } else {
87
88
  play.stop(now, down: input.down)
@@ -91,7 +92,7 @@ struct CharacterSim {
91
92
  restSince = now
92
93
  // The stroll is over: sent home again, it rests there.
93
94
  strolled = 0; strollTo = 0; strollNext = nil
94
- } else if input.held {
95
+ } else if held {
95
96
  target = x
96
97
  awayUntil = max(awayUntil, now + Self.awayFor)
97
98
  } else if let to = game.target {
@@ -133,7 +134,7 @@ struct CharacterSim {
133
134
  if let at = pending, now >= at { pending = nil; go(goal, now) }
134
135
  var pose = change.pose(at: now)
135
136
  // Idle, left alone and standing: a small animation now and then.
136
- let alone = mood == .idle && input.activity == .idle && input.asked == nil && !input.sent && !input.held && !input.shows
137
+ let alone = mood == .idle && input.activity == .idle && input.asked == nil && !input.sent && !held && !input.shows
137
138
  && !near && game == PointerPlay.Out() && play.game == nil && abs(speed) < 40 && strolled == 0 && strollTo == 0
138
139
  let own = idle.step(now, dt, free: alone, gap: input.animates, dozeIn: restSince + Self.dozeAfter - now)
139
140
 
@@ -12,6 +12,9 @@ extension CharacterSim {
12
12
  /// The pointer is on its speech bubble: it stays where it is, so
13
13
  /// the bubble is not pulled from under the pointer.
14
14
  var held = false
15
+ /// It can be clicked (`CharacterMath.clickable`): it waits for a
16
+ /// pointer that comes close, and plays no game with it (#579).
17
+ var clickable = false
15
18
  /// The answering agent sent it to show something (#482): it goes
16
19
  /// to `home` at once, awake, whatever the pointer did before.
17
20
  var sent = false
@@ -12,15 +12,18 @@ final class CharacterView: NSView {
12
12
  /// Its speech bubble in this window, origin bottom-left; nil while hidden.
13
13
  var bubble: NSRect?
14
14
 
15
- /// A drag of its body. Its window takes the mouse for nothing else.
15
+ /// A press on its body: a drag, or a click when it did not move.
16
16
  enum Drag { case began, moved, ended }
17
17
  var onDrag: ((Drag) -> Void)?
18
+ /// A right-click on its body.
19
+ var onMenu: ((NSEvent) -> Void)?
18
20
 
19
21
  override var isFlipped: Bool { true }
20
22
  override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true }
21
23
  override func mouseDown(with event: NSEvent) { onDrag?(.began) }
22
24
  override func mouseDragged(with event: NSEvent) { onDrag?(.moved) }
23
25
  override func mouseUp(with event: NSEvent) { onDrag?(.ended) }
26
+ override func rightMouseDown(with event: NSEvent) { onMenu?(event) }
24
27
 
25
28
  override func draw(_ dirtyRect: NSRect) {
26
29
  guard let ctx = NSGraphicsContext.current?.cgContext else { return }
@@ -477,6 +477,8 @@ final class App: NSObject, NSApplicationDelegate {
477
477
 
478
478
  registerHotkeys()
479
479
  panel.onClick = { [weak self] in self?.toggleListening() }
480
+ character.onClick = { [weak self] in self?.toggleListening() }
481
+ character.contextMenu = { [weak self] in self?.statusMenu.menu ?? NSMenu() }
480
482
  statusMenu.onSettings = { [weak self] in self?.settingsWindow.show() }
481
483
  settingsWindow.model.onSaved = { [weak self] saved in self?.apply(saved) }
482
484
  // While a shortcut field waits for keys, ours stand aside so the
@@ -1,2 +1,2 @@
1
- import{A as a,B as b,C as c}from"./chunk-HVPRCHRG.js";import"./chunk-SFQUP3BP.js";import"./chunk-QOYAX2FT.js";import"./chunk-5MUJZODV.js";import"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import"./chunk-QIJLFPWE.js";export{a as createAgentContext,b as generate,c as generateStream};
2
- //# sourceMappingURL=agent-MUGC4RZP.js.map
1
+ import{A as a,B as b,C as c}from"./chunk-MZQQVT3G.js";import"./chunk-SFQUP3BP.js";import"./chunk-QOYAX2FT.js";import"./chunk-5MUJZODV.js";import"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import"./chunk-QIJLFPWE.js";export{a as createAgentContext,b as generate,c as generateStream};
2
+ //# sourceMappingURL=agent-NPE76XHC.js.map
@@ -1,4 +1,4 @@
1
- import{$ as Gl,Aa as Dr,Ba as Ql,Ca as Zl,D as vl,Da as ed,Ea as td,F as Sl,Ga as nd,H as Il,I as Er,J as $l,K as Le,L as Tl,M as Cr,Na as sd,O as Pr,Oa as rd,P as xl,Q as _r,R as Fe,S as Dl,T as Nl,W as Ue,X as jl,Xa as Nr,Y as Ll,Ya as jr,Z as Fl,_ as Ul,_a as id,a as Nc,aa as Hl,b as Sr,ca as le,da as bn,ea as Or,f as Ir,fa as Bl,g as jc,ga as kn,h as Lc,ha as Wl,i as Ae,ia as ke,j as Fc,ja as ql,k as Uc,ka as Vl,la as Jl,m as Gc,ma as vn,na as Sn,o as Hc,oa as Xl,p as nl,pa as Kl,q as sl,r as rl,s as il,t as ol,u as al,ua as zl,v as cl,ya as Yl,z as wn,za as In}from"./chunk-NWNVHL57.js";import{c as _c,f as Oc,g as Dc}from"./chunk-25RQQ55U.js";import{c as Ol}from"./chunk-DG5I6PPM.js";import{a as Bc}from"./chunk-ZVP6GB4G.js";import{m as Wc,n as qc,o as Tr,p as Re,r as Vc,s as ge}from"./chunk-S2GAEH2F.js";import{a as bl,b as kl}from"./chunk-VZLIBDLH.js";import{b as Al,c as Rl,d as Mr,e as El,f as Cl,g as Pl,h as Ml,i as _l}from"./chunk-EKJG63EJ.js";import{o as $r}from"./chunk-IOPAWHKW.js";import{b as xr}from"./chunk-ACFQBLPX.js";import{g as Jc}from"./chunk-LQE73AZR.js";import{b as Xc,c as Kc}from"./chunk-2D3RYIDU.js";import{i as dl,m as Rr,n as ul,p as hl,q as gl,r as pl,s as ml,t as fl,u as yl}from"./chunk-3Z5P2CWS.js";import{b as Ar,c as zc,d as Yc,e as fn,g as yn,i as Qc,j as Zc,k as el,l as tl,o as ll}from"./chunk-E5OV6RTG.js";import{a as wl}from"./chunk-PPUN7YHA.js";import{A as Ba,B as Wa,C as qa,D as se,E as Ja,F as Xa,G as Ka,H as za,I as wc,J as bc,K as kc,L as vc,M as Sc,N as Ic,P as xc,Z as Ac,a as ba,b as pr,c as va,d as Ta,e as xa,f as $t,h as mr,i as fr,j as yr,k as Aa,l as Ra,s as Ea,t as Ma,u as Tt,v as _a,w as Na,x as G,z as Ha}from"./chunk-UXTAK5WD.js";import{B as Tc,a as Ca,c as Oa,d as Da,e as je,f as Qe,l as Ya,m as Qa,o as dc,p as uc,q as mc,r as fc,t as yc,v as $c}from"./chunk-FZ7VHFL5.js";import{b as ic,c as oc,d as kr,f as hn,g as ac,h as cc,i as lc,j as xt,k as gn}from"./chunk-GLQLCBJS.js";import{a as wr,b as Pa}from"./chunk-DP7RTNDM.js";import{A as Rc,B as pn,C as Ec,h as Jo,n as Xo,o as sr}from"./chunk-HVPRCHRG.js";import{b as Wo}from"./chunk-SFQUP3BP.js";import{a as At}from"./chunk-Y4CYQV7G.js";import{a as Cc,b as mn,c as Pc,d as Mc}from"./chunk-LLNPKE7H.js";import{a as et,b as tt}from"./chunk-SHEUCITK.js";import{a as Za,b as br,c as ec,d as tc,e as nc,i as sc}from"./chunk-76Z4VHDX.js";import{b as Va}from"./chunk-W4YR2RO2.js";import{b as ne,d as Ze,f as ln,g as dn,i as ie,j as rc,k as Te,l as xe,m as pc,s as vr}from"./chunk-MVLNVMWI.js";import{a as hc,b as gc}from"./chunk-OLUAEBHJ.js";import{d as ja,e as La,f as Fa,g as Ua,h as Ga,j as un}from"./chunk-X5C5W3E4.js";import{c as wa}from"./chunk-MYVHVJWZ.js";import{d as Sa,e as Ia,j as $a}from"./chunk-DWADWDMU.js";import{b as ka}from"./chunk-2GIDVZ4H.js";import{d as Ko,e as Sf,m as ma,n as Pf,o as fa,t as ya,v as Ye,w as cn}from"./chunk-HE4PDESB.js";import{a as Ne,b as It,f as gr}from"./chunk-72SZI2UW.js";import{a as rr,b as vf}from"./chunk-FCPTN6NF.js";import{a as nn,b as kf}from"./chunk-7I7IEX4S.js";import{b as qo,e as Vo}from"./chunk-JHCI6XCJ.js";import{e as _e}from"./chunk-DSYKYZMT.js";import{A as ur,C as ia,D as oa,E as an,F as aa,G as ca,H as la,I as da,J as Rf,L as ua,O as ha,P as ga,T as Ef,d as ze,e as zo,ea as hr,f as ir,fa as pa,g as $f,h as sn,ha as Cf,i as or,j as rn,l as Oe,m as ar,p as on,q as Tf,w as sa,x as Af,y as ra}from"./chunk-IA3BC7M3.js";import{a as lr,b as Zo,c as ea,d as dr,e as ta,f as na,i as xf}from"./chunk-RJ7DASOU.js";import{e as De,f as Yo,g as Qo,h as cr}from"./chunk-BRK6M6LA.js";import{e as If}from"./chunk-2QNT5JDS.js";import{d as Ke}from"./chunk-QIJLFPWE.js";import{existsSync as Mf,readFileSync as _f}from"fs";var od=["answer","narration","line"];function ad(r){return r==="/voice/queue"||r.startsWith("/voice/queue/")}async function cd(r,e,t,n,s){if(n==="/voice/queue"){if(t==="GET")return{status:200,body:r.view()};if(t!=="POST")return{status:405,body:{error:"GET or POST"}};let c=String(s.text??"").trim(),l=String(s.agentId??s.agent??""),d=String(s.kind??"line");if(!c||!l||!od.includes(d))return{status:400,body:{error:`Required: text and agentId; kind is ${od.join(" | ")}`}};if(c.length>5e3)return{status:413,body:{error:"text is over 5000 characters"}};let u=e(l);if(!u)return{status:404,body:{error:`Unknown agent: ${l}`}};let{item:g,done:m}=r.enqueue({voice:u,text:c,agentId:l,kind:d});return s.wait!==!0?{status:202,body:{item:g}}:{status:200,body:{item:g,played:await m}}}if(t==="POST"&&n==="/voice/queue/pause")return r.pause(),{status:200,body:r.view()};if(t==="POST"&&n==="/voice/queue/resume")return r.resume(),{status:200,body:r.view()};let[,,,i,o,a]=n.split("/");if(t!=="POST"||!i||a!==void 0)return{status:404,body:{error:"Not found"}};switch(o){case"skip":return r.skip(i)?{status:200,body:r.view()}:Lr(i);case"front":return r.front(i)?{status:200,body:r.view()}:Lr(i);case"replay":{let c=r.replay(i);return c?{status:202,body:{item:c}}:Lr(i)}default:return{status:404,body:{error:"Not found"}}}}function ld(r){let e=n=>`${n.agentId??"someone"} (${n.kind}): "${n.text.length>80?`${n.text.slice(0,79)}\u2026`:n.text}" [${n.id}]`;return[r.playing?`Speaking: ${e(r.playing)}`:r.paused?"Paused: the listener is speaking; the queue plays on after.":"Nothing is speaking.",...r.waiting.map((n,s)=>`${s+1}. waiting: ${e(n)}`)].join(`
1
+ import{$ as Gl,Aa as Dr,Ba as Ql,Ca as Zl,D as vl,Da as ed,Ea as td,F as Sl,Ga as nd,H as Il,I as Er,J as $l,K as Le,L as Tl,M as Cr,Na as sd,O as Pr,Oa as rd,P as xl,Q as _r,R as Fe,S as Dl,T as Nl,W as Ue,X as jl,Xa as Nr,Y as Ll,Ya as jr,Z as Fl,_ as Ul,_a as id,a as Nc,aa as Hl,b as Sr,ca as le,da as bn,ea as Or,f as Ir,fa as Bl,g as jc,ga as kn,h as Lc,ha as Wl,i as Ae,ia as ke,j as Fc,ja as ql,k as Uc,ka as Vl,la as Jl,m as Gc,ma as vn,na as Sn,o as Hc,oa as Xl,p as nl,pa as Kl,q as sl,r as rl,s as il,t as ol,u as al,ua as zl,v as cl,ya as Yl,z as wn,za as In}from"./chunk-NWNVHL57.js";import{c as _c,f as Oc,g as Dc}from"./chunk-25RQQ55U.js";import{c as Ol}from"./chunk-DG5I6PPM.js";import{a as Bc}from"./chunk-ZVP6GB4G.js";import{m as Wc,n as qc,o as Tr,p as Re,r as Vc,s as ge}from"./chunk-S2GAEH2F.js";import{a as bl,b as kl}from"./chunk-VZLIBDLH.js";import{b as Al,c as Rl,d as Mr,e as El,f as Cl,g as Pl,h as Ml,i as _l}from"./chunk-EKJG63EJ.js";import{o as $r}from"./chunk-IOPAWHKW.js";import{b as xr}from"./chunk-ACFQBLPX.js";import{g as Jc}from"./chunk-LQE73AZR.js";import{b as Xc,c as Kc}from"./chunk-2D3RYIDU.js";import{i as dl,m as Rr,n as ul,p as hl,q as gl,r as pl,s as ml,t as fl,u as yl}from"./chunk-3Z5P2CWS.js";import{b as Ar,c as zc,d as Yc,e as fn,g as yn,i as Qc,j as Zc,k as el,l as tl,o as ll}from"./chunk-E5OV6RTG.js";import{a as wl}from"./chunk-PPUN7YHA.js";import{A as Ba,B as Wa,C as qa,D as se,E as Ja,F as Xa,G as Ka,H as za,I as wc,J as bc,K as kc,L as vc,M as Sc,N as Ic,P as xc,Z as Ac,a as ba,b as pr,c as va,d as Ta,e as xa,f as $t,h as mr,i as fr,j as yr,k as Aa,l as Ra,s as Ea,t as Ma,u as Tt,v as _a,w as Na,x as G,z as Ha}from"./chunk-DEMIKEFB.js";import{B as Tc,a as Ca,c as Oa,d as Da,e as je,f as Qe,l as Ya,m as Qa,o as dc,p as uc,q as mc,r as fc,t as yc,v as $c}from"./chunk-FZ7VHFL5.js";import{b as ic,c as oc,d as kr,f as hn,g as ac,h as cc,i as lc,j as xt,k as gn}from"./chunk-GLQLCBJS.js";import{a as wr,b as Pa}from"./chunk-DP7RTNDM.js";import{A as Rc,B as pn,C as Ec,h as Jo,n as Xo,o as sr}from"./chunk-MZQQVT3G.js";import{b as Wo}from"./chunk-SFQUP3BP.js";import{a as At}from"./chunk-Y4CYQV7G.js";import{a as Cc,b as mn,c as Pc,d as Mc}from"./chunk-LLNPKE7H.js";import{a as et,b as tt}from"./chunk-SHEUCITK.js";import{a as Za,b as br,c as ec,d as tc,e as nc,i as sc}from"./chunk-76Z4VHDX.js";import{b as Va}from"./chunk-W4YR2RO2.js";import{b as ne,d as Ze,f as ln,g as dn,i as ie,j as rc,k as Te,l as xe,m as pc,s as vr}from"./chunk-MVLNVMWI.js";import{a as hc,b as gc}from"./chunk-OLUAEBHJ.js";import{d as ja,e as La,f as Fa,g as Ua,h as Ga,j as un}from"./chunk-X5C5W3E4.js";import{c as wa}from"./chunk-MYVHVJWZ.js";import{d as Sa,e as Ia,j as $a}from"./chunk-DWADWDMU.js";import{b as ka}from"./chunk-2GIDVZ4H.js";import{d as Ko,e as Sf,m as ma,n as Pf,o as fa,t as ya,v as Ye,w as cn}from"./chunk-HE4PDESB.js";import{a as Ne,b as It,f as gr}from"./chunk-72SZI2UW.js";import{a as rr,b as vf}from"./chunk-FCPTN6NF.js";import{a as nn,b as kf}from"./chunk-7I7IEX4S.js";import{b as qo,e as Vo}from"./chunk-JHCI6XCJ.js";import{e as _e}from"./chunk-DSYKYZMT.js";import{A as ur,C as ia,D as oa,E as an,F as aa,G as ca,H as la,I as da,J as Rf,L as ua,O as ha,P as ga,T as Ef,d as ze,e as zo,ea as hr,f as ir,fa as pa,g as $f,h as sn,ha as Cf,i as or,j as rn,l as Oe,m as ar,p as on,q as Tf,w as sa,x as Af,y as ra}from"./chunk-IA3BC7M3.js";import{a as lr,b as Zo,c as ea,d as dr,e as ta,f as na,i as xf}from"./chunk-RJ7DASOU.js";import{e as De,f as Yo,g as Qo,h as cr}from"./chunk-BRK6M6LA.js";import{e as If}from"./chunk-2QNT5JDS.js";import{d as Ke}from"./chunk-QIJLFPWE.js";import{existsSync as Mf,readFileSync as _f}from"fs";var od=["answer","narration","line"];function ad(r){return r==="/voice/queue"||r.startsWith("/voice/queue/")}async function cd(r,e,t,n,s){if(n==="/voice/queue"){if(t==="GET")return{status:200,body:r.view()};if(t!=="POST")return{status:405,body:{error:"GET or POST"}};let c=String(s.text??"").trim(),l=String(s.agentId??s.agent??""),d=String(s.kind??"line");if(!c||!l||!od.includes(d))return{status:400,body:{error:`Required: text and agentId; kind is ${od.join(" | ")}`}};if(c.length>5e3)return{status:413,body:{error:"text is over 5000 characters"}};let u=e(l);if(!u)return{status:404,body:{error:`Unknown agent: ${l}`}};let{item:g,done:m}=r.enqueue({voice:u,text:c,agentId:l,kind:d});return s.wait!==!0?{status:202,body:{item:g}}:{status:200,body:{item:g,played:await m}}}if(t==="POST"&&n==="/voice/queue/pause")return r.pause(),{status:200,body:r.view()};if(t==="POST"&&n==="/voice/queue/resume")return r.resume(),{status:200,body:r.view()};let[,,,i,o,a]=n.split("/");if(t!=="POST"||!i||a!==void 0)return{status:404,body:{error:"Not found"}};switch(o){case"skip":return r.skip(i)?{status:200,body:r.view()}:Lr(i);case"front":return r.front(i)?{status:200,body:r.view()}:Lr(i);case"replay":{let c=r.replay(i);return c?{status:202,body:{item:c}}:Lr(i)}default:return{status:404,body:{error:"Not found"}}}}function ld(r){let e=n=>`${n.agentId??"someone"} (${n.kind}): "${n.text.length>80?`${n.text.slice(0,79)}\u2026`:n.text}" [${n.id}]`;return[r.playing?`Speaking: ${e(r.playing)}`:r.paused?"Paused: the listener is speaking; the queue plays on after.":"Nothing is speaking.",...r.waiting.map((n,s)=>`${s+1}. waiting: ${e(n)}`)].join(`
2
2
  `)}var Lr=r=>({status:404,body:{error:`No such line in the queue: ${r}`}});import{resolve as Of}from"path";var Df={name:"agentx",version:"0.1.0"},Nf="2024-11-05",jf={tools:{},elicitation:{form:{}}},Lf=0;async function dd(r,e){let t=++Lf;return Ge({jsonrpc:"2.0",id:`elicit-${t}`,method:"elicitation/create",params:{mode:"form",message:r,requestedSchema:e}}),new Promise(n=>{Rt.set(`elicit-${t}`,s=>{s?.action==="accept"&&s.content?n(s.content):n(null)}),setTimeout(()=>{Rt.has(`elicit-${t}`)&&(Rt.delete(`elicit-${t}`),n(null))},6e4)})}var Rt=new Map,Ff="http://localhost:19900",Fr;function Uf(){if(process.env.AGENTX_DAEMON_URL)return process.env.AGENTX_DAEMON_URL;for(let r of["agentx.json",".agentx/config.json"])try{let e=Of(process.cwd(),r);if(!Mf(e))continue;let t=JSON.parse(_f(e,"utf-8"))?.node?.bind;if(typeof t!="string"||!t.includes(":"))continue;{let n=t.lastIndexOf(":"),s=t.slice(0,n),i=t.slice(n+1),o=!s||s==="0.0.0.0"||s==="::"||s==="*"?"127.0.0.1":s;if(i)return`http://${o}:${i}`}}catch{}return Ff}function V(){return Fr===void 0&&(Fr=Uf()),Fr}function Ur(r=process.env){let e={};return r.AGENTX_TASK_ID&&(e.callerTaskId=r.AGENTX_TASK_ID),r.AGENTX_CHANNEL&&(e.callerChannel=r.AGENTX_CHANNEL),r.AGENTX_CHAT_ID&&(e.callerChatId=r.AGENTX_CHAT_ID),e}async function Gf(){let r=process.env.AGENTX_AGENT_ID,e=Ur();if(!(!r||!e.callerChannel||!e.callerChatId))try{let t=new URLSearchParams({channel:e.callerChannel,chatId:e.callerChatId}),n=await fetch(`${V()}/agents/${encodeURIComponent(r)}/intent-path?${t}`,{signal:AbortSignal.timeout(2e3)});if(!n.ok)return;let s=await n.json();return{...Array.isArray(s.path)&&s.path.length?{path:s.path}:{},...typeof s.graphWeight=="number"?{graphWeight:s.graphWeight}:{}}}catch{return}}var Hf=/\x1B\[[0-9;]*[A-Za-z]/g;function nt(r){return r.replace(Hf,"")}function Bf(r,e,t){if(!e.subscriptions)return`${r} has no event subscriptions. Add agents.${r}.subscriptions to agentx.json to receive events.`;let n=e.events??[];return n.length===0?`No new events match ${r}'s subscriptions.${e.next?` next: ${e.next}`:""}`:[...n.map(s=>`- ${t(s)} [id ${s.id}, root ${s.rootId}]`),`next: ${e.next}`].join(`
3
3
  `)}var Wf=[{name:"agentx_generate",description:"Generate code, components, pages, APIs, documents, tests, workflows, schemas, emails, diagrams, and more using AI. Understands the project's tech stack, schemas, and skills automatically.",inputSchema:{type:"object",properties:{task:{type:"string",description:"Describe what to generate (e.g., 'a responsive pricing card', 'REST API for users', 'GitHub Actions CI pipeline')"},type:{type:"string",description:"Output type: component, page, api, website, document, script, config, skill, media, report, test, workflow, schema, email, diagram, auto",default:"auto"},output_dir:{type:"string",description:"Optional output directory (relative to project root)"},cwd:{type:"string",description:"Project working directory (defaults to current directory)"}},required:["task"]}},{name:"agentx_inspect",description:"Analyze a project and return its tech stack, frameworks, databases, schemas, installed skills, and dependencies. Use this to understand a project before generating code.",inputSchema:{type:"object",properties:{cwd:{type:"string",description:"Project working directory (defaults to current directory)"}}}},{name:"agentx_skill_match",description:"Find installed skills that are relevant to a given task description. Returns matched skills with relevance scores.",inputSchema:{type:"object",properties:{task:{type:"string",description:"The task to match skills against"},cwd:{type:"string",description:"Project working directory"}},required:["task"]}},{name:"agentx_detect_output_type",description:"Auto-detect the best output type for a given task description based on keyword analysis.",inputSchema:{type:"object",properties:{task:{type:"string",description:"The task description to analyze"}},required:["task"]}},{name:"agentx_channel_reply",description:"Reply to a channel (GitLab issue/MR comment, GitHub issue/PR comment, Telegram/WhatsApp message). PREFER THIS over raw curl/glab/HTTP \u2014 it auto-applies agent identity from agentMappings, the cascade-prevention marker, intent-ledger audit, and a 60s body-hash dedupe so an accidental retry within the window is a no-op. Returns the posted message id. For agent-to-agent delegation use agentx_send_agent. For arbitrary outbound sends use agentx_send.",inputSchema:{type:"object",properties:{channel:{type:"string",description:"Channel name. gitlab | github | telegram | whatsapp | discord | slack"},chatId:{type:"string",description:"Stable chat id you received in this task's context. GitLab: 'org/repo:issue:123' or 'org/repo:merge_request:123'. GitHub: 'org/repo:issue:123' or 'org/repo:pull:123'. Telegram: numeric. WhatsApp: '+phone@s.whatsapp.net'."},text:{type:"string",description:"Reply body. Markdown for gitlab/github/discord; plain for sms/whatsapp."},agentId:{type:"string",description:"Optional posting identity. Defaults to channel-adapter resolution from agentMappings."},accountId:{type:"string",description:"Multi-account adapters (telegram) need this when the chat is reachable from more than one bot."},replyTo:{type:"string",description:"Optional reply-to message id for threaded channels."},idempotencyKey:{type:"string",description:"Optional explicit dedupe key. When omitted, a body hash is used. Use a stable key for 'overwrite my last status update' patterns."}},required:["channel","chatId","text"]}},{name:"agentx_channel_label",description:"Add and/or remove labels on a GitLab issue or merge_request through the canonical adapter (per-agent token, ledger). Use this instead of curl when changing labels on the entity that triggered the current task.",inputSchema:{type:"object",properties:{channel:{type:"string",description:"Currently 'gitlab'.",default:"gitlab"},project:{type:"string",description:"GitLab project path \u2014 'org/repo'."},kind:{type:"string",description:"'issue' or 'merge_request'."},iid:{type:"string",description:"Numeric iid as a string."},add:{type:"array",items:{type:"string"},description:"Labels to add."},remove:{type:"array",items:{type:"string"},description:"Labels to remove."},agentId:{type:"string",description:"Optional posting identity."}},required:["project","kind","iid"]}},{name:"agentx_send",description:"Low-level outbound send when you ALREADY have a channel-native chatId (Telegram numeric chat id, GitLab 'group/project:issue:123', WhatsApp '+phone@s.whatsapp.net'). For sending to another agent by name, use agentx_send_agent instead. For sending to a human contact by name, use agentx_send_contact instead.",inputSchema:{type:"object",properties:{channel:{type:"string",description:"Target channel: telegram, whatsapp, gitlab, discord"},chatId:{type:"string",description:'Chat ID. Telegram: numeric ("-1001234567890"). GitLab: "group/project:issue:123". WhatsApp: "+phone@s.whatsapp.net".'},text:{type:"string",description:"Message text to send"},agentId:{type:"string",description:"Agent ID to send as (determines bot account on Telegram, GitLab token, etc.)"}},required:["channel","chatId","text"]}},{name:"agentx_send_agent",description:"Send a message to ANOTHER AGENT by exact agentId \u2014 uses the AgentX A2A mesh (or local registry when the agent lives on this daemon). This is the deterministic path for agent-to-agent communication; it never falls through to a contact lookup, so an unknown agentId returns 404 with the list of known agents instead of silently sending to a similarly-named human. Use this when the target is a registered agent. When a person started this conversation, the call returns at once with a task id; tell the person who you asked, end your turn, and the answer arrives later as a new message in this conversation.",inputSchema:{type:"object",properties:{agentId:{type:"string",description:"Exact agentId of the target agent (e.g. 'peer', 'atlas'). Must match an agent in this daemon's registry or in a healthy mesh peer's directory."},text:{type:"string",description:"Message to send to the target agent"},senderAgentId:{type:"string",description:"Optional. The agentId on whose behalf this call is being made. Recorded in route_traces and (with A2A protocolVersion >= 2) validated by the receiving daemon."}},required:["agentId","text"]}},{name:"agentx_recent",description:"Read the most recent messages from a chat across ALL agents that have sessions for it. Returns inbound + each agent's replies in chronological order, so you can see what's actually been said in a Telegram chat / GitLab thread / WhatsApp DM regardless of which agent recorded it. Use this BEFORE speculating about what was sent \u2014 the cx/devops/marketing thread on 2026-04-29 about a Marketing/CX bot mixup would have been resolved in one call instead of three agents speculating. Bounded by sinceISO (default: last 24h) and limit (default: 30, max: 200).",inputSchema:{type:"object",properties:{channel:{type:"string",description:"Channel name. Examples: telegram, whatsapp, gitlab, github, discord, cron, api, a2a."},chatId:{type:"string",description:'Channel-native chat id. Telegram: numeric (e.g. "1816212449" for a DM, "-1001234567890" for a group). GitLab: "group/project:issue:123". WhatsApp: "+phone@s.whatsapp.net".'},sinceISO:{type:"string",description:"Optional ISO timestamp lower bound. Defaults to 24h ago."},limit:{type:"number",description:"Optional cap on returned messages. Default 30, max 200."}},required:["channel","chatId"]}},{name:"agentx_events",description:"Read what happened on this node that matches your event subscriptions (agents.<id>.subscriptions in agentx.json): tasks other agents finished or failed, workflow runs, mesh hand-offs. Use it to catch up after being idle instead of asking. Returns short summaries only (no prompts or answers), oldest first, at most 50. Pass the `next` value from the previous answer as `since` to read only newer events.",inputSchema:{type:"object",properties:{since:{type:"string",description:"An event id (events after it) or an ISO time. Default: the newest events in memory."},limit:{type:"number",description:"Most events to return. Default 20, max 50."},agentId:{type:"string",description:"Whose subscriptions to read. Ignored when the AgentX runtime already identifies you (AGENTX_AGENT_ID)."}}}},{name:"agentx_send_contact",description:"Send a message to a HUMAN CONTACT by name. Resolves through .agentx/contacts.json (id \u2192 exact alias \u2192 fuzzy substring). Refuses fuzzy matches without confirmed:true so the agent must ask the user to disambiguate before sending. Refuses when the name also matches a registered agent (use agentx_send_agent for those). Use this when the target is a person, not a bot.",inputSchema:{type:"object",properties:{contactName:{type:"string",description:"Free-form contact name. Tried as id first, then alias, then fuzzy substring."},text:{type:"string",description:"Message to send to the contact"},channel:{type:"string",description:"Optional explicit channel (telegram | whatsapp | gitlab | discord). Defaults to the first channel configured for the contact."},confirmed:{type:"boolean",description:"Pass true ONLY after the user has confirmed a fuzzy match. Without it, fuzzy matches return 409 with the candidate so you can ask the user."},agentId:{type:"string",description:"Optional agent identity used for the outbound send (determines bot account / token)."}},required:["contactName","text"]}},{name:"agentx_task",description:"Send a task to a specific agent on the daemon. The agent processes it and returns a response. Use to delegate work to specialized agents. When a person started this conversation, the call returns at once with a task id instead: tell the person who you asked and why, then end your turn. The answer arrives later as a new message in this same conversation.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to send the task to"},message:{type:"string",description:"Task message for the agent"},senderAgentId:{type:"string",description:"Optional caller agent id. Defaults to AGENTX_AGENT_ID when the MCP server was launched by an AgentX runtime."},freshSession:{type:"boolean",description:"Start the target agent with a clean AgentX-side conversation. Defaults to true for agent-to-agent delegation."},chatId:{type:"string",description:"Optional stable chat/session id for this delegated task. Omit for a one-off isolated delegation."}},required:["agent","message"]}},{name:"agentx_agents",description:"List all agents registered on the daemon with their status (active tasks, total tasks, errors, tier).",inputSchema:{type:"object",properties:{}}},{name:"agentx_voice_queue",description:"See what this host is saying out loud and what waits to be said: every agent's spoken answers, narration, talks and lessons share one speaking queue. Use it before speaking at length, or when asked who is talking.",inputSchema:{type:"object",properties:{}}},{name:"agentx_call_owner",description:"Ring the owner for a live voice call on their desktop widget, when you need them directly and a message will not do. When they answer you speak first, so give the reason in one line. Only agents the owner allowed (calls.allow) can call; a few calls an hour at most. urgency 'urgent' rings through Focus: use it only for something that cannot wait. Returns how it rang, or why it did not.",inputSchema:{type:"object",properties:{reason:{type:"string",description:"Why you are calling, in one line (at most 200 characters)."},urgency:{type:"string",enum:["normal","urgent"],description:"Default normal: held as a missed call during Focus."}},required:["reason"]}},{name:"agentx_camera_ask",description:"Ask the owner to show you their phone camera, when you need to see something (a rack, a cable, a document). The ask shows on their phone; the camera opens only if they tap Show. Same allowlist and hourly limit as calls (calls.allow). Once they share, call agentx_camera_look for the newest picture. Returns whether the owner was told, or why not.",inputSchema:{type:"object",properties:{reason:{type:"string",description:"What you want to see, in one line (at most 200 characters)."},urgency:{type:"string",enum:["normal","urgent"],description:"Default normal: held during Focus."}},required:["reason"]}},{name:"agentx_camera_look",description:"The newest picture from the owner's phone camera while they share it with you, saved as a PNG. Open the returned path with your Read tool to look at it. Fails when no share is live for you.",inputSchema:{type:"object",properties:{}}},{name:"agentx_health",description:"Get the daemon health status including node info, agents, crons, mesh peers, and uptime.",inputSchema:{type:"object",properties:{}}},{name:"agentx_attach_next",description:"Take the next message queued for the agent identity THIS session is attached to (attach mode). Returns the message plus who sent it and on which channel, or nothing when the inbox is empty. After calling this, just answer normally \u2014 your reply is captured automatically and sent back to the channel. Use when the user runs /inbox or asks you to check for waiting messages.",inputSchema:{type:"object",properties:{}}},{name:"agentx_attach_answer",description:"Explicitly answer the message currently claimed by this session (attach mode). Usually unnecessary \u2014 replying normally after agentx_attach_next is captured automatically. Use this only when your reply to the channel should differ from what you told the user in the terminal.",inputSchema:{type:"object",properties:{text:{type:"string",description:"The reply to send back to the channel, verbatim."}},required:["text"]}},{name:"agentx_crons",description:"List cron jobs and their health. Shows healthy, failing, disabled counts and per-job status with consecutive error counts.",inputSchema:{type:"object",properties:{}}},{name:"agentx_schedule",description:"Manage recurring routines (schedules) in plain English. Actions: list, create, pause, resume, delete. create and delete are REQUESTS: nothing takes effect until the operator approves (the operator is sent the parsed cron and next fire time). Tell the user it is pending approval. You can pause/resume/delete only routines you created, unless you are an admin agent. Example: {action:'create', when:'every monday at 10am', prompt:'Check the open invoices and summarise'}.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["list","create","pause","resume","delete"],description:"What to do. Default: list."},id:{type:"string",description:"Schedule id. Required for pause/resume/delete; optional for create (auto-generated)."},when:{type:"string",description:"create: plain-English timing, e.g. 'every monday at 10am', 'weekdays at 6pm', 'every 15 minutes', '1st of every month at noon'."},prompt:{type:"string",description:"create: what the agent should do at each run."},agent:{type:"string",description:"create: agent that runs the routine. Default: you."},timezone:{type:"string",description:"create: IANA timezone. Default: the node's schedule default."},notify:{type:"string",description:"create: where results/failures go. 'here' (default: the current chat), 'none', or 'channel:chatId'."},mine:{type:"boolean",description:"list: only routines you created."},channel:{type:"string",description:"Current chat's channel, from your task context. Used as the default notify target when the runtime didn't provide it."},chatId:{type:"string",description:"Current chat id, from your task context."},accountId:{type:"string",description:"Optional bot account for multi-account channels."},callerAgentId:{type:"string",description:"Your agent id. Ignored when the AgentX runtime already identifies you (AGENTX_AGENT_ID)."}}}},{name:"agentx_approval",description:"Ask the operator for a yes/no decision by raising a decision card in their Approvals inbox, instead of asking in chat. Lead with your recommendation. Every card expires: say what should happen if nobody answers (if_silent). You get a message with the result when it is decided or expires. You cannot approve anything with this tool. Actions: create (default), status. To offer ready-made answers, add choices (and optionally a draft message); the operator's pick and final text come back with the result. Example: {title:'Publish the launch post draft', ask:'Publish the draft on Monday?', recommend:'Yes: it is reviewed and the date is agreed', if_silent:'discard', expires:'2d', source:'https://example.com/drafts/42'}.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["create","status"],description:"create (default) or status."},title:{type:"string",description:"create: what it is, in one line (max 120 characters)."},ask:{type:"string",description:"create: the yes/no question (max 300 characters)."},recommend:{type:"string",description:"create: your advice and why, in one line (max 300 characters). With choices, start with the exact label you advise: the Mac card marks it and opens with it picked."},if_silent:{type:"string",enum:["discard","keep","pause","approve"],description:"create: what applies if nobody answers before it expires."},expires:{type:"string",description:"create: when the default applies. ISO date/time, or relative like '12h' or '3d'. Default: the node's setting (3 days)."},source:{type:"string",description:"create: link to the draft, PR or issue."},choices:{type:"array",items:{type:"string"},description:"create, optional: 1-5 ready-made answers the operator picks from (e.g. three free meeting slots). A yes then carries the pick."},draft:{type:"string",description:"create, optional: a suggested message the operator may edit before approving. {choice} is replaced by the pick. On yes you get the final text: send exactly that."},say:{type:"string",description:"create, optional: one short line the Mac popup speaks (max 160 characters). Default: the title."},context:{type:"string",description:"create, optional: a few lines of background shown above the question, e.g. what the other person said (max 600 characters)."},id:{type:"string",description:"status: the card id you got from create."},channel:{type:"string",description:"Current chat's channel, from your task context, so the result can mention it."},chatId:{type:"string",description:"Current chat id, from your task context."},callerAgentId:{type:"string",description:"Your agent id. Ignored when the AgentX runtime already identifies you (AGENTX_AGENT_ID)."}}}},{name:"agentx_request",description:"Say what you are doing with a request the owner gave you, so it stays on their list of open requests until it is closed. Use accept when the work goes on after this turn; wait when the next step is the owner's answer (give the question); done when it is finished (give a link to the evidence: PR, issue, message, deploy); decline when you will not do it (give the reason). list shows what is still open, oldest first: use it when the owner asks what is still open. Without an id, the action applies to the request of the turn you are in; for an older request pass its id (list shows them). You cannot drop a request; only the owner can. Example: {action:'done', evidence:'https://example.com/pull/42'}.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["accept","wait","done","decline","list"],description:"list (default), accept, wait, done or decline."},id:{type:"string",description:"The request id, when it is not the request of this turn."},question:{type:"string",description:"wait: what you are asking the owner."},evidence:{type:"string",description:"done: a link to the proof (PR, issue, message, deploy)."},reason:{type:"string",description:"decline: why you will not do it."},channel:{type:"string",description:"Current chat's channel, from your task context."},chatId:{type:"string",description:"Current chat id, from your task context."},callerAgentId:{type:"string",description:"Your agent id. Ignored when the AgentX runtime already identifies you (AGENTX_AGENT_ID)."}}}},{name:"agentx_debug",description:"Toggle debug mode on the daemon. Enable verbose logging for specific categories (webhook, agent, channel, cron, mesh, context, memory, all) or disable it.",inputSchema:{type:"object",properties:{action:{type:"string",description:'"on", "off", or "status"',default:"status"},categories:{type:"string",description:'Comma-separated categories to enable (e.g. "webhook,agent"). Only used with action=on.'}}}},{name:"agentx_wiki_query",description:"Query the agentx institutional wiki: a cross-agent knowledge base organized by article type (person, project, place, concept, event, decision, pattern). Use this BEFORE grep/memory-search when the question is about who / what happened / what we decided / how we do something. The query walks the catalog + wikilink graph and returns a synthesized answer with citations.",inputSchema:{type:"object",properties:{question:{type:"string",description:"The question to answer from the wiki, in natural language."},agent:{type:"string",description:"Which agent's wiki to query (default: first agent with a catalog). Each agent has its own wiki dir under .agentx/wiki/agents/<id>/"},wiki_dir:{type:"string",description:"Wiki root dir (default: <cwd>/.agentx/wiki)."},max_hops:{type:"number",description:"Wikilink hops from candidates (default 2, max 3).",default:2}},required:["question"]}},{name:"agentx_wiki_patch",description:"Edit a single wiki article via an LLM-applied instruction and write the result. Use this for targeted fixes, additions, or clarifications to an existing article when you already know what's wrong. For brand-new articles, use `agentx_wiki_interview` instead.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID whose wiki owns the article (required)."},title_or_path:{type:"string",description:"Article title (case-insensitive) or relative path like 'people/alex.md'."},instruction:{type:"string",description:"Plain-English edit instruction (e.g. 'Add a section on the KSA Supabase rollout'). The LLM makes the minimum edit that satisfies it."},model:{type:"string",description:"Claude model for the patch (default: sonnet).",default:"sonnet"},dry_run:{type:"boolean",description:"Preview the patched body without writing.",default:!1}},required:["agent","title_or_path","instruction"]}},{name:"agentx_wiki_interview",description:"Run a scripted wiki interview \u2014 synthesize ONE typed article from a list of Q&A answers, and save it. Non-interactive: caller supplies the answers upfront. Use for capturing tacit knowledge (person/project/decision/pattern/...) that never hit a channel. For editing an existing article, use `agentx_wiki_patch`.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID that will own the new article (required)."},topic:{type:"string",description:"What the article is about \u2014 e.g. 'Globex deployment procedure', 'Jane Doe', 'DemoSite KSA migration'."},type:{type:"string",description:"Article type: person | project | place | concept | event | decision | pattern"},answers:{type:"array",description:"Answers to the type-specific question bank (one per question, in order). Empty string = skip that question. Final entry is typically 'save'.",items:{type:"string"}},model:{type:"string",description:"Synthesis model (default: sonnet).",default:"sonnet"},commit:{type:"boolean",description:"Write the article (true) or just preview (false).",default:!0}},required:["agent","topic","type","answers"]}},{name:"agentx_graph_review",description:"Triage pending intent-graph classifications via the configured review agent. The review agent sees each pending classification, may call `wiki query` for institutional context, and decides approve/reject/skip. Structural changes (new org, new unit) gate here; leaf additions auto-approve without this step.",inputSchema:{type:"object",properties:{max:{type:"number",description:"Cap reviews this run (default 20).",default:20},dry_run:{type:"boolean",description:"Show decisions but don't apply approvals/rejections.",default:!1},agent:{type:"string",description:"Override the review agent (defaults to graph.reviewAgent or graph.draftAgent)."}}}}];async function qf(r,e){let t=e.cwd||process.cwd();switch(r){case"agentx_generate":{let n=e.task,s=e.type||"auto",i=e.output_dir,o=await pn({task:n,outputType:s,outputDir:i,cwd:t,overwrite:!0,dryRun:!1,context7:!0,interactive:!1,maxSteps:5}),a=[];return o.content&&a.push(o.content),o.files.written.length&&a.push(`
4
4
  Created ${o.files.written.length} file(s):
@@ -512,7 +512,7 @@ ${l}`)}let S={agentId:o,message:v,context:{channel:w,sender:f?"opencode":"openai
512
512
 
513
513
  `)}}function xu(r){r.writeHead(200,{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache",Connection:"keep-alive","X-Accel-Buffering":"no"})}function Au(r,e,t,n,s,i){r.write(`data: ${JSON.stringify({id:e,object:"chat.completion.chunk",created:t,model:n,choices:[{index:0,delta:s,finish_reason:i}]})}
514
514
 
515
- `)}function Ru(r,e,t,n,s,i){let o=i?.usage?.inputTokens??0,a=i?.usage?.outputTokens??Math.ceil(s.length/4);ui(r,200,{id:e,object:"chat.completion",created:t,model:n,choices:[{index:0,message:{role:"assistant",content:s},finish_reason:"stop"}],usage:{prompt_tokens:o,completion_tokens:a,total_tokens:o+a}})}function ui(r,e,t){r.writeHead(e,{"Content-Type":"application/json"}),r.end(JSON.stringify(t))}var jt=class{module;minLevel;constructor(e,t="info"){this.module=e,this.minLevel=t}child(e){return new jt(`${this.module}:${e}`,this.minLevel)}debug(e,t){this.emit("debug",e,t)}info(e,t){this.emit("info",e,t)}warn(e,t){this.emit("warn",e,t)}error(e,t){this.emit("error",e,t)}asConsoleLog(){return(...e)=>{let n=e.map(s=>typeof s=="string"?s:JSON.stringify(s)).join(" ").replace(/^\[agentx\]\s*/,"");n&&this.info(n)}}emit(e,t,n){if(jt.levelOrder[e]<jt.levelOrder[this.minLevel])return;let s={time:new Date().toISOString(),level:e,module:this.module,msg:t,...n},i=e==="error"?"ERROR":e==="warn"?"WARN":"",o=`[${this.module}]`,a=i?`${o} ${i}: ${t}`:`${o} ${t}`;console.error(a)}},Nt=jt;Ke(Nt,"levelOrder",{debug:0,info:1,warn:2,error:3});import{realpathSync as Hw,statSync as Bw}from"fs";var lt={version:"0.103.2",commit:"1dca0e7",startedAt:new Date(Date.now()-process.uptime()*1e3).toISOString()};function Ww(r,e){let t=e.mtimeMs!==null&&e.mtimeMs>Date.parse(r.startedAt),n=!!e.version&&!!r.version&&e.version!==r.version;return{newer:t||n,changedAt:e.mtimeMs===null?null:new Date(e.mtimeMs).toISOString(),version:e.version}}function Cu(){let r=null;try{r=Bw(Hw(process.argv[1])).mtimeMs}catch{}let e=zd().version;return Ww(lt,{mtimeMs:r,version:e&&e!=="0.0.0"?e:null})}import{randomUUID as qw}from"crypto";var Xn=class{constructor(e=new Na){this.core=e}count=0;subscribe(e,t){this.count++;let n=this.core.subscribe((i,o)=>{if(!o||!Vw.includes(o.kind))return;let a={...o,rootId:i.rootId,node:i.node};Xw(e,a)&&t(a)}),s=!0;return()=>{s&&(s=!1,this.count--,n())}}publish(e){let t={id:typeof e.id=="string"?e.id:qw(),at:typeof e.at=="string"?e.at:new Date().toISOString(),...e},{type:n,summary:s,ref:i,agentId:o}=Jw(t);this.core.publish({id:t.id,at:t.at,kind:t.kind,type:n,summary:s,ref:i,agentId:o,rootId:typeof e.rootId=="string"?e.rootId:void 0,data:t})}get size(){return this.count}},Vw=["run","task","signal","mesh","channel","status"];function Jw(r){switch(r.kind){case"run":return{type:r.phase,ref:r.runId,summary:[r.workflowId,r.nodeId,r.phase,r.note].filter(Boolean).join(" ")};case"task":return{type:r.phase,ref:r.taskId,summary:`${r.title??r.taskId} ${r.phase}`};case"signal":return{type:"emitted",summary:`signal ${r.name} (${r.scope})`};case"mesh":return{type:r.delta,summary:`peer ${r.peer} ${r.delta}`};case"channel":return{type:r.direction,ref:r.messageId,agentId:r.agentId,summary:`${r.channel} ${r.direction==="in"?"inbound":"outbound"}`};case"status":return{type:"status",summary:r.message}}}function Xw(r,e){return!(r.kinds&&r.kinds.length>0&&!r.kinds.includes(e.kind)||r.workflowId&&(e.kind==="run"&&e.workflowId!==r.workflowId||e.kind==="task"&&e.workflowId!==r.workflowId||e.kind==="signal"&&e.workflowId&&e.workflowId!==r.workflowId)||r.runId&&(e.kind==="run"&&e.runId!==r.runId||e.kind==="task"&&e.runId!==r.runId)||r.actor&&(e.kind!=="task"||!(e.assignedTo?.includes(r.actor)||e.submittedBy===r.actor))||r.channel&&(e.kind!=="channel"||e.channel!==r.channel))}function Pu(r){if(!r)return;let e=["run","task","signal","mesh","channel","status"],n=r.split(",").map(s=>s.trim()).filter(Boolean).filter(s=>e.includes(s));return n.length?n:void 0}import{createHmac as Kn,timingSafeEqual as Mu}from"crypto";var zn=class{registry;config;mesh;webhookEntries;log;workflowDispatcher;hooks;constructor(e,t={},n=console.error.bind(console,"[webhook]"),s,i=[],o){this.registry=e,this.config=t,this.log=n,this.mesh=s,this.webhookEntries=i,this.hooks=o}hookEventFor(e,t){if(e==="stripe")return"on:stripe-event";if(e==="sentry")return"on:sentry-issue";if(e==="vercel")return"on:vercel-deployment";if(e==="hubspot")return"on:hubspot-event";if(e==="odoo")return"on:odoo-event";if(e==="github"){let n=(t??"").split(".")[0];return n==="issues"||n==="issue_comment"?"on:github-issue":n==="pull_request"||n==="pull_request_review"?"on:github-pr":n==="push"?"on:github-push":null}return null}async fireHookSafe(e,t,n,s){let i=this.hookEventFor(e,t);if(!i||!this.hooks||!this.hooks.has(i))return;let o={};if(e==="github"){let a=s;typeof a.sender?.login=="string"&&(o.author=a.sender.login),typeof a.repository?.full_name=="string"&&(o.repo=a.repository.full_name);let c=a.issue?.number??a.pull_request?.number;typeof c=="number"&&(o.number=c)}try{await this.hooks.execute(i,{event:i,source:e,eventType:t,agentId:n,payload:s,...o})}catch(a){this.log(`${i} hook error (non-fatal): ${a?.message??a}`)}}setWorkflowDispatcher(e){this.workflowDispatcher=e}setWebhookEntries(e){this.webhookEntries=e}async handle(e,t,n){let s=n.replace(/^\/webhook\/?/,"").split("/").filter(Boolean),i=s[0],o=s[1];if(!i){this.sendJson(t,400,{error:"Missing agent ID. Use /webhook/:agentId"});return}let{raw:a,parsed:c}=await this.readBody(e),l=o||this.detectSource(e.headers);if(process.env.AGENTX_WEBHOOK_DEBUG_HEADERS==="1"){let k={};for(let[v,S]of Object.entries(e.headers))(v.startsWith("x-hubspot")||v.startsWith("x-hub")||v.startsWith("x-github")||v.startsWith("x-gitlab")||v.startsWith("stripe")||v.startsWith("sentry")||v.startsWith("x-vercel")||v.startsWith("x-odoo")||v.startsWith("x-webhook")||v==="user-agent"||v==="content-type"||v==="host"||v==="x-forwarded-host"||v==="x-forwarded-proto"||v==="x-forwarded-for")&&(k[v]=S);this.log(`Webhook [${l}] reqUrl=${e.url} headers: ${JSON.stringify(k)}`)}let d=this.validateSignature(e.headers,a,l,i,e.url);if(d){this.log(`Webhook [${l}] -> ${i}: REJECTED (${d})`),this.sendJson(t,401,{error:d});return}let u=this.buildSummary(l,c,e.headers);this.log(`Webhook [${l}] -> ${i}: ${u.slice(0,100)}`);let g=this.extractEventType(l,c,e.headers),m=this.webhookEntries.find(k=>k.enabled&&k.agentId===i&&k.source===l),f=g&&m?.triggers?.[g]||m?.defaultWorkflow||null;if(await this.fireHookSafe(l,g,i,c),f&&this.workflowDispatcher)try{let k=await this.workflowDispatcher.dispatchWorkflow({workflowId:f,entityRef:{kind:"webhook",id:`${l}:${i}:${g??"\u2014"}:${Date.now()}`},event:{kind:"webhook",source:l,eventType:g,payload:c},trigger:{source:l}});this.log(`Webhook [${l}/${g??"\u2014"}] -> workflow=${f} (claimed=${k.claimed})`),this.sendJson(t,202,{ok:!0,agent:i,source:l,eventType:g,workflow:f,claimed:k.claimed});return}catch(k){this.log(`Workflow dispatch failed [${l}/${g}/${f}]: ${k.message}`)}let w=this.webhookEntries.find(k=>k.enabled&&k.node&&k.agentId===i&&k.source===l);if(w?.node&&this.mesh){this.sendJson(t,202,{ok:!0,agent:i,source:l,node:w.node,status:"accepted"}),this.mesh.sendTask(w.node,u,i,{context:{channel:`webhook:${l}`,sender:`webhook:${l}`}}).then(k=>this.log(`Mesh-forwarded webhook [${l}] -> ${w.node}/${i}: ${k?.slice(0,100)||"ok"}`),k=>this.log(`Mesh forward failed [${l}] -> ${w.node}/${i}: ${k.message}`));return}try{let k=await this.registry.execute({message:u,agentId:i,context:{channel:`webhook:${l}`,sender:`webhook:${l}`}});this.sendJson(t,k.error?500:200,{ok:!k.error,agent:i,source:l,response:k.content?.slice(0,500),error:k.error,duration:k.duration})}catch(k){this.sendJson(t,500,{error:k.message})}}extractEventType(e,t,n){let s=i=>{let o=n[i.toLowerCase()];return Array.isArray(o)?o[0]:o};if(e==="github"){let i=s("x-github-event");if(!i)return;let o=typeof t.action=="string"?t.action:void 0;return o?`${i}.${o}`:i}if(e==="gitlab")return s("x-gitlab-event")||(typeof t.object_kind=="string"?t.object_kind:void 0);if(e==="stripe")return typeof t.type=="string"?t.type:void 0;if(e==="sentry")return s("sentry-hook-resource");if(e==="hubspot"){if(Array.isArray(t)&&t.length>0){let i=t[0];if(i&&typeof i.subscriptionType=="string")return i.subscriptionType}return typeof t.subscriptionType=="string"?t.subscriptionType:void 0}if(e==="odoo")return typeof t.event=="string"?t.event:typeof t.subscriptionType=="string"?t.subscriptionType:typeof t.model=="string"?typeof t.action=="string"?`${t.model}.${t.action}`:t.model:void 0}detectSource(e){return e["x-gitlab-event"]||e["x-gitlab-token"]?"gitlab":e["x-github-event"]?"github":e["stripe-signature"]?"stripe":e["sentry-hook-resource"]?"sentry":e["x-vercel-signature"]?"vercel":e["x-hubspot-signature-v3"]||e["x-hubspot-signature-version"]?"hubspot":e["x-odoo-database"]||e["x-odoo-signature"]?"odoo":e["x-hub-signature-256"]?"github":"unknown"}buildSummary(e,t,n){let s=[`[Webhook from ${e}]`];switch(e){case"gitlab":{let o=n["x-gitlab-event"]||t.object_kind||"event",a=t.project?.path_with_namespace||"",c=t.user?.name||t.user_username||"";if(s.push(`Event: ${o}`),a&&s.push(`Project: ${a}`),c&&s.push(`User: ${c}`),t.ref&&s.push(`Ref: ${t.ref}`),t.commits&&Array.isArray(t.commits)){s.push(`Commits: ${t.commits.length}`);for(let d of t.commits.slice(0,3))s.push(` - ${d.message?.split(`
515
+ `)}function Ru(r,e,t,n,s,i){let o=i?.usage?.inputTokens??0,a=i?.usage?.outputTokens??Math.ceil(s.length/4);ui(r,200,{id:e,object:"chat.completion",created:t,model:n,choices:[{index:0,message:{role:"assistant",content:s},finish_reason:"stop"}],usage:{prompt_tokens:o,completion_tokens:a,total_tokens:o+a}})}function ui(r,e,t){r.writeHead(e,{"Content-Type":"application/json"}),r.end(JSON.stringify(t))}var jt=class{module;minLevel;constructor(e,t="info"){this.module=e,this.minLevel=t}child(e){return new jt(`${this.module}:${e}`,this.minLevel)}debug(e,t){this.emit("debug",e,t)}info(e,t){this.emit("info",e,t)}warn(e,t){this.emit("warn",e,t)}error(e,t){this.emit("error",e,t)}asConsoleLog(){return(...e)=>{let n=e.map(s=>typeof s=="string"?s:JSON.stringify(s)).join(" ").replace(/^\[agentx\]\s*/,"");n&&this.info(n)}}emit(e,t,n){if(jt.levelOrder[e]<jt.levelOrder[this.minLevel])return;let s={time:new Date().toISOString(),level:e,module:this.module,msg:t,...n},i=e==="error"?"ERROR":e==="warn"?"WARN":"",o=`[${this.module}]`,a=i?`${o} ${i}: ${t}`:`${o} ${t}`;console.error(a)}},Nt=jt;Ke(Nt,"levelOrder",{debug:0,info:1,warn:2,error:3});import{realpathSync as Hw,statSync as Bw}from"fs";var lt={version:"0.104.0",commit:"ed2e469",startedAt:new Date(Date.now()-process.uptime()*1e3).toISOString()};function Ww(r,e){let t=e.mtimeMs!==null&&e.mtimeMs>Date.parse(r.startedAt),n=!!e.version&&!!r.version&&e.version!==r.version;return{newer:t||n,changedAt:e.mtimeMs===null?null:new Date(e.mtimeMs).toISOString(),version:e.version}}function Cu(){let r=null;try{r=Bw(Hw(process.argv[1])).mtimeMs}catch{}let e=zd().version;return Ww(lt,{mtimeMs:r,version:e&&e!=="0.0.0"?e:null})}import{randomUUID as qw}from"crypto";var Xn=class{constructor(e=new Na){this.core=e}count=0;subscribe(e,t){this.count++;let n=this.core.subscribe((i,o)=>{if(!o||!Vw.includes(o.kind))return;let a={...o,rootId:i.rootId,node:i.node};Xw(e,a)&&t(a)}),s=!0;return()=>{s&&(s=!1,this.count--,n())}}publish(e){let t={id:typeof e.id=="string"?e.id:qw(),at:typeof e.at=="string"?e.at:new Date().toISOString(),...e},{type:n,summary:s,ref:i,agentId:o}=Jw(t);this.core.publish({id:t.id,at:t.at,kind:t.kind,type:n,summary:s,ref:i,agentId:o,rootId:typeof e.rootId=="string"?e.rootId:void 0,data:t})}get size(){return this.count}},Vw=["run","task","signal","mesh","channel","status"];function Jw(r){switch(r.kind){case"run":return{type:r.phase,ref:r.runId,summary:[r.workflowId,r.nodeId,r.phase,r.note].filter(Boolean).join(" ")};case"task":return{type:r.phase,ref:r.taskId,summary:`${r.title??r.taskId} ${r.phase}`};case"signal":return{type:"emitted",summary:`signal ${r.name} (${r.scope})`};case"mesh":return{type:r.delta,summary:`peer ${r.peer} ${r.delta}`};case"channel":return{type:r.direction,ref:r.messageId,agentId:r.agentId,summary:`${r.channel} ${r.direction==="in"?"inbound":"outbound"}`};case"status":return{type:"status",summary:r.message}}}function Xw(r,e){return!(r.kinds&&r.kinds.length>0&&!r.kinds.includes(e.kind)||r.workflowId&&(e.kind==="run"&&e.workflowId!==r.workflowId||e.kind==="task"&&e.workflowId!==r.workflowId||e.kind==="signal"&&e.workflowId&&e.workflowId!==r.workflowId)||r.runId&&(e.kind==="run"&&e.runId!==r.runId||e.kind==="task"&&e.runId!==r.runId)||r.actor&&(e.kind!=="task"||!(e.assignedTo?.includes(r.actor)||e.submittedBy===r.actor))||r.channel&&(e.kind!=="channel"||e.channel!==r.channel))}function Pu(r){if(!r)return;let e=["run","task","signal","mesh","channel","status"],n=r.split(",").map(s=>s.trim()).filter(Boolean).filter(s=>e.includes(s));return n.length?n:void 0}import{createHmac as Kn,timingSafeEqual as Mu}from"crypto";var zn=class{registry;config;mesh;webhookEntries;log;workflowDispatcher;hooks;constructor(e,t={},n=console.error.bind(console,"[webhook]"),s,i=[],o){this.registry=e,this.config=t,this.log=n,this.mesh=s,this.webhookEntries=i,this.hooks=o}hookEventFor(e,t){if(e==="stripe")return"on:stripe-event";if(e==="sentry")return"on:sentry-issue";if(e==="vercel")return"on:vercel-deployment";if(e==="hubspot")return"on:hubspot-event";if(e==="odoo")return"on:odoo-event";if(e==="github"){let n=(t??"").split(".")[0];return n==="issues"||n==="issue_comment"?"on:github-issue":n==="pull_request"||n==="pull_request_review"?"on:github-pr":n==="push"?"on:github-push":null}return null}async fireHookSafe(e,t,n,s){let i=this.hookEventFor(e,t);if(!i||!this.hooks||!this.hooks.has(i))return;let o={};if(e==="github"){let a=s;typeof a.sender?.login=="string"&&(o.author=a.sender.login),typeof a.repository?.full_name=="string"&&(o.repo=a.repository.full_name);let c=a.issue?.number??a.pull_request?.number;typeof c=="number"&&(o.number=c)}try{await this.hooks.execute(i,{event:i,source:e,eventType:t,agentId:n,payload:s,...o})}catch(a){this.log(`${i} hook error (non-fatal): ${a?.message??a}`)}}setWorkflowDispatcher(e){this.workflowDispatcher=e}setWebhookEntries(e){this.webhookEntries=e}async handle(e,t,n){let s=n.replace(/^\/webhook\/?/,"").split("/").filter(Boolean),i=s[0],o=s[1];if(!i){this.sendJson(t,400,{error:"Missing agent ID. Use /webhook/:agentId"});return}let{raw:a,parsed:c}=await this.readBody(e),l=o||this.detectSource(e.headers);if(process.env.AGENTX_WEBHOOK_DEBUG_HEADERS==="1"){let k={};for(let[v,S]of Object.entries(e.headers))(v.startsWith("x-hubspot")||v.startsWith("x-hub")||v.startsWith("x-github")||v.startsWith("x-gitlab")||v.startsWith("stripe")||v.startsWith("sentry")||v.startsWith("x-vercel")||v.startsWith("x-odoo")||v.startsWith("x-webhook")||v==="user-agent"||v==="content-type"||v==="host"||v==="x-forwarded-host"||v==="x-forwarded-proto"||v==="x-forwarded-for")&&(k[v]=S);this.log(`Webhook [${l}] reqUrl=${e.url} headers: ${JSON.stringify(k)}`)}let d=this.validateSignature(e.headers,a,l,i,e.url);if(d){this.log(`Webhook [${l}] -> ${i}: REJECTED (${d})`),this.sendJson(t,401,{error:d});return}let u=this.buildSummary(l,c,e.headers);this.log(`Webhook [${l}] -> ${i}: ${u.slice(0,100)}`);let g=this.extractEventType(l,c,e.headers),m=this.webhookEntries.find(k=>k.enabled&&k.agentId===i&&k.source===l),f=g&&m?.triggers?.[g]||m?.defaultWorkflow||null;if(await this.fireHookSafe(l,g,i,c),f&&this.workflowDispatcher)try{let k=await this.workflowDispatcher.dispatchWorkflow({workflowId:f,entityRef:{kind:"webhook",id:`${l}:${i}:${g??"\u2014"}:${Date.now()}`},event:{kind:"webhook",source:l,eventType:g,payload:c},trigger:{source:l}});this.log(`Webhook [${l}/${g??"\u2014"}] -> workflow=${f} (claimed=${k.claimed})`),this.sendJson(t,202,{ok:!0,agent:i,source:l,eventType:g,workflow:f,claimed:k.claimed});return}catch(k){this.log(`Workflow dispatch failed [${l}/${g}/${f}]: ${k.message}`)}let w=this.webhookEntries.find(k=>k.enabled&&k.node&&k.agentId===i&&k.source===l);if(w?.node&&this.mesh){this.sendJson(t,202,{ok:!0,agent:i,source:l,node:w.node,status:"accepted"}),this.mesh.sendTask(w.node,u,i,{context:{channel:`webhook:${l}`,sender:`webhook:${l}`}}).then(k=>this.log(`Mesh-forwarded webhook [${l}] -> ${w.node}/${i}: ${k?.slice(0,100)||"ok"}`),k=>this.log(`Mesh forward failed [${l}] -> ${w.node}/${i}: ${k.message}`));return}try{let k=await this.registry.execute({message:u,agentId:i,context:{channel:`webhook:${l}`,sender:`webhook:${l}`}});this.sendJson(t,k.error?500:200,{ok:!k.error,agent:i,source:l,response:k.content?.slice(0,500),error:k.error,duration:k.duration})}catch(k){this.sendJson(t,500,{error:k.message})}}extractEventType(e,t,n){let s=i=>{let o=n[i.toLowerCase()];return Array.isArray(o)?o[0]:o};if(e==="github"){let i=s("x-github-event");if(!i)return;let o=typeof t.action=="string"?t.action:void 0;return o?`${i}.${o}`:i}if(e==="gitlab")return s("x-gitlab-event")||(typeof t.object_kind=="string"?t.object_kind:void 0);if(e==="stripe")return typeof t.type=="string"?t.type:void 0;if(e==="sentry")return s("sentry-hook-resource");if(e==="hubspot"){if(Array.isArray(t)&&t.length>0){let i=t[0];if(i&&typeof i.subscriptionType=="string")return i.subscriptionType}return typeof t.subscriptionType=="string"?t.subscriptionType:void 0}if(e==="odoo")return typeof t.event=="string"?t.event:typeof t.subscriptionType=="string"?t.subscriptionType:typeof t.model=="string"?typeof t.action=="string"?`${t.model}.${t.action}`:t.model:void 0}detectSource(e){return e["x-gitlab-event"]||e["x-gitlab-token"]?"gitlab":e["x-github-event"]?"github":e["stripe-signature"]?"stripe":e["sentry-hook-resource"]?"sentry":e["x-vercel-signature"]?"vercel":e["x-hubspot-signature-v3"]||e["x-hubspot-signature-version"]?"hubspot":e["x-odoo-database"]||e["x-odoo-signature"]?"odoo":e["x-hub-signature-256"]?"github":"unknown"}buildSummary(e,t,n){let s=[`[Webhook from ${e}]`];switch(e){case"gitlab":{let o=n["x-gitlab-event"]||t.object_kind||"event",a=t.project?.path_with_namespace||"",c=t.user?.name||t.user_username||"";if(s.push(`Event: ${o}`),a&&s.push(`Project: ${a}`),c&&s.push(`User: ${c}`),t.ref&&s.push(`Ref: ${t.ref}`),t.commits&&Array.isArray(t.commits)){s.push(`Commits: ${t.commits.length}`);for(let d of t.commits.slice(0,3))s.push(` - ${d.message?.split(`
516
516
  `)[0]||"no message"} (${d.author?.name||""})`)}let l=t.object_attributes;if(l?.title&&(s.push(`Title: ${l.title}`),s.push(`State: ${l.state||""}`),s.push(`Action: ${l.action||""}`),l.source_branch&&s.push(`Branch: ${l.source_branch} -> ${l.target_branch}`),l.url&&s.push(`URL: ${l.url}`)),l?.iid&&!l?.source_branch&&(s.push(`Issue #${l.iid}: ${l.title||""}`),l.description&&s.push(`Description: ${l.description.slice(0,200)}`)),t.object_kind==="pipeline"){let d=t.object_attributes;s.push(`Pipeline: ${d?.status||""} (${d?.ref||""})`),s.push(`Duration: ${d?.duration||0}s`)}break}case"github":{let o=n["x-github-event"]||"event",a=t.repository?.full_name||"",c=t.sender?.login||"";if(s.push(`Event: ${o}`),a&&s.push(`Repository: ${a}`),c&&s.push(`Sender: ${c}`),t.ref&&s.push(`Ref: ${t.ref}`),t.commits&&Array.isArray(t.commits))for(let u of t.commits.slice(0,3))s.push(` - ${u.message?.split(`
517
517
  `)[0]||""} (${u.author?.name||""})`);let l=t.pull_request;l&&(s.push(`PR #${l.number}: ${l.title}`),s.push(`Action: ${t.action}`),s.push(`Branch: ${l.head?.ref} -> ${l.base?.ref}`));let d=t.issue;d&&(s.push(`Issue #${d.number}: ${d.title}`),s.push(`Action: ${t.action}`));break}case"stripe":{let o=t.type||"event",a=t.data?.object||{};s.push(`Event: ${o}`),a.amount&&s.push(`Amount: ${(a.amount/100).toFixed(2)} ${a.currency?.toUpperCase()||""}`),a.customer_email&&s.push(`Customer: ${a.customer_email}`),a.description&&s.push(`Description: ${a.description}`),a.status&&s.push(`Status: ${a.status}`);break}case"sentry":{let o=n["sentry-hook-resource"]||"event";s.push(`Resource: ${o}`);let a=t.data||t;a.error?.title&&s.push(`Error: ${a.error.title}`),a.error?.culprit&&s.push(`Culprit: ${a.error.culprit}`),a.error?.metadata?.value&&s.push(`Message: ${a.error.metadata.value}`),t.url&&s.push(`URL: ${t.url}`);break}case"hubspot":{let o=Array.isArray(t)?t:null,a=o||null;if(a&&a.length){s.push(`Events: ${a.length}`);for(let l of a.slice(0,3)){let d=l.subscriptionType??"?",u=l.objectId??"?",g=l.changeFlag??l.changeSource??"";s.push(` - ${d} (object ${u}${g?`, ${g}`:""})`)}}else{let l=t.subscriptionType??"event",d=t.objectId??"?";s.push(`Event: ${l} (object ${d})`)}let c=a?.[0]?.portalId??t.portalId;c!=null&&s.push(`Portal: ${c}`);break}case"odoo":{let o=typeof t.event=="string"&&t.event||typeof t.subscriptionType=="string"&&t.subscriptionType||typeof t.model=="string"&&(typeof t.action=="string"?`${t.model}.${t.action}`:t.model)||"event";s.push(`Event: ${o}`);let a=n["x-odoo-database"]||(typeof t.database=="string"?t.database:"");a&&s.push(`Database: ${a}`);let c=t.record||t;c?.id&&s.push(`Record id: ${c.id}`),c?.name&&s.push(`Name: ${String(c.name).slice(0,200)}`),c?.partner_id?.[1]&&s.push(`Partner: ${c.partner_id[1]}`),c?.email&&s.push(`Email: ${c.email}`),c?.amount_total!=null&&s.push(`Amount: ${c.amount_total}`),c?.state&&s.push(`State: ${c.state}`);break}default:s.push(`Headers: ${JSON.stringify(Object.keys(n).filter(o=>o.startsWith("x-")).slice(0,5))}`),s.push(`Payload keys: ${Object.keys(t).slice(0,10).join(", ")}`);let i=JSON.stringify(t).slice(0,500);s.push(`Body: ${i}`)}return s.join(`
518
518
  `)}async readBody(e){return new Promise(t=>{let n="";e.on("data",s=>n+=s.toString()),e.on("end",()=>{let s;try{s=n?JSON.parse(n):{}}catch{s={raw:n}}t({raw:n,parsed:s})}),e.on("error",()=>t({raw:"",parsed:{}}))})}validateSignature(e,t,n,s,i){let o=this.webhookEntries.find(d=>d.enabled&&d.agentId===s&&d.source===n);if(!o?.secretEnv)return null;let a=process.env[o.secretEnv];if(!a)return`webhook entry "${o.id}" expects env ${o.secretEnv} but it is unset`;let c=d=>{let u=e[d.toLowerCase()];return Array.isArray(u)?u[0]:u};if(n==="github"){let d=c("x-hub-signature-256");if(!d)return"missing X-Hub-Signature-256";let u="sha256="+Kn("sha256",a).update(t).digest("hex");return dt(u,d)}if(n==="gitlab"){let d=c("x-gitlab-token");return d?dt(a,d):"missing X-Gitlab-Token"}if(n==="stripe"){let d=c("stripe-signature");if(!d)return"missing Stripe-Signature";let u=Object.fromEntries(d.split(",").map(m=>m.split("=")));if(!u.t||!u.v1)return"malformed Stripe-Signature";let g=Kn("sha256",a).update(`${u.t}.${t}`).digest("hex");return dt(g,u.v1)}if(n==="hubspot"){let d=c("x-hubspot-signature-v3"),u=c("x-hubspot-request-timestamp");if(!d)return"missing X-HubSpot-Signature-v3";if(!u)return"missing X-HubSpot-Request-Timestamp";let g=parseInt(u,10);if(!Number.isFinite(g))return"malformed X-HubSpot-Request-Timestamp";let m=Date.now()-g;if(m>5*6e4)return`HubSpot webhook is ${Math.floor(m/1e3)}s old (>5min replay window)`;let f="POST",w=i||e["x-original-uri"]||e["x-forwarded-path"]||"",k=e["x-forwarded-host"],v=e.host,S=e["x-forwarded-proto"]||"https",I=new Set;k&&w&&I.add(`${S}://${k}${w}`),v&&w&&I.add(`https://${v}${w}`),v&&w&&I.add(`http://${v}${w}`),w&&I.add(w),I.add("");for(let A of I){let D=Kn("sha256",a).update(`${f}${A}${t}${u}`).digest("base64");if(d.length===D.length&&Mu(Buffer.from(d),Buffer.from(D)))return null}return`signature mismatch (tried ${I.size} URI variants)`}if(n==="odoo"){let d=c("x-odoo-signature");if(d){let g=Kn("sha256",a).update(t).digest("hex"),m=d.startsWith("sha256=")?d.slice(7):d;return dt(g,m)}let u=c("x-odoo-webhook-token")??c("x-webhook-secret");return u?dt(a,u):"missing X-Odoo-Signature or X-Odoo-Webhook-Token"}let l=c("x-webhook-secret");return l?dt(a,l):"missing X-Webhook-Secret"}sendJson(e,t,n){e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify(n,null,2))}};function dt(r,e){if(r.length!==e.length)return"signature mismatch";let t=Buffer.from(r),n=Buffer.from(e);return Mu(t,n)?null:"signature mismatch"}xf();vf();function Kw(r){return{insertTaskHistory:r.prepare(`
@@ -1138,4 +1138,4 @@ data: ${JSON.stringify(W)}
1138
1138
  `)}catch{}},O=setInterval(()=>{try{t.write(`: ping
1139
1139
 
1140
1140
  `)}catch{}},15e3);O.unref?.();let j=new AbortController;t.on("close",()=>{t.writableEnded||j.abort()});try{for await(let N of this.mesh.sendTaskStream(h.peer,h.message,h.agent,{context:h.context,signal:j.signal,vouchOwner:b}))x(N.event,N.data)}catch(N){x("error",{error:N?.message??String(N)})}finally{clearInterval(O);try{t.end()}catch{}}break}let M=h.context,P=typeof h.senderAgentId=="string"?h.senderAgentId:void 0;if(zm(h,!0)==="callback"){let x=this.delegationGate(e,h,{callee:h.agent,peer:h.peer,message:h.message,calleeContext:M});if(!("track"in x)){let O=Vs(x);this.json(t,O.status,O.body);break}}if(h.async===!0){let x=M?.channel,O=M?.chatId;if(!x||!O){this.json(t,400,{error:"async requires context.channel and context.chatId \u2014 there is no route back otherwise"});return}let j=`mesh-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;this.json(t,202,{accepted:!0,taskId:j,deliverTo:`${x}:${O}`,note:"result will be delivered to the originating chat when the peer finishes"});let N=h.peer,W=h.agent,Y=this.mesh;(async()=>{let B=Date.now(),H;try{H=await Y.sendTask(N,h.message,W,{vouchOwner:b,context:M,senderAgentId:P}),this.log(`[mesh/task async ${j}] ${N}/${W??"default"} finished in ${Date.now()-B}ms`)}catch(X){H=`Delegation to ${N}/${W??"default"} failed: ${X?.message??X}`,this.log(`[mesh/task async ${j}] failed: ${X?.message??X}`)}try{await this.router.sendOutbound({channel:x,chatId:O,text:H,agentId:M?.agentId??P,accountId:M?.accountId})}catch(X){this.log(`[mesh/task async ${j}] delivery failed: ${X?.message??X}`)}})();break}let C=await this.mesh.sendTask(h.peer,h.message,h.agent,{context:M,senderAgentId:P,vouchOwner:b});this.json(t,200,{response:C});break}case"POST /webrtc/signal/out":{if(!this.webrtc){this.json(t,404,{error:"WebRTC signaling not enabled"});return}let p=await U(e);if(!p.kind||!p.callId||!p.from||!p.to){this.json(t,400,{error:"Missing: kind, callId, from, to"});return}let y=await this.webrtc.handleOutgoing(p);this.json(t,y.ok?200:400,y);break}case"POST /webrtc/signal":{if(!this.webrtc){this.json(t,404,{error:"WebRTC signaling not enabled"});return}let p=await U(e);if(!p.kind||!p.callId||!p.from||!p.to){this.json(t,400,{error:"Missing: kind, callId, from, to"});return}let y=this.webrtc.handleIncoming(p);this.json(t,y.ok?200:400,y);break}case"POST /webrtc/bot/invite":{if(!this.botManager){this.json(t,404,{error:"WebRTC bot not enabled (channels.webrtc.bot.enabled=false)"});return}let h=await U(e),p=h.callId,y=h.target,b=h.agentId||this.config.channels.webrtc?.bot.defaultAgentId;if(!p||!y||!b){this.json(t,400,{error:"Missing: callId, target, agentId (or defaultAgentId in config)"});return}let $=await this.botManager.invite({callId:p,target:y,agentId:b});this.json(t,$.ok?200:500,$);break}case"GET /webrtc/bots":{if(!this.botManager){this.json(t,404,{error:"WebRTC bot not enabled"});return}this.json(t,200,{active:this.botManager.active()});break}case"GET /webrtc/history":{if(!this.botManager){this.json(t,404,{error:"WebRTC bot not enabled"});return}this.json(t,200,{active:this.botManager.active(),history:this.botManager.history()});break}case"GET /webrtc/config":{let h=this.config.channels.webrtc;if(!h?.enabled){this.json(t,404,{error:"WebRTC signaling not enabled"});return}this.json(t,200,{localName:this.config.node.name,iceServers:[...h.stunServers.map(p=>({urls:p})),...h.turnServers],peers:this.mesh?.directory().map(p=>({name:p.peer,healthy:p.healthy}))||[],camera:h.camera,agents:this.registry.list().map(p=>({id:p.id,name:p.name}))});break}case"GET /.well-known/agent-card.json":this.json(t,200,{name:this.config.node.name,description:`AgentX daemon node "${this.config.node.name}"`,url:`http://${this.config.node.bind}`,version:"1.0.0",capabilities:{streaming:!1,pushNotifications:!1,stateTransitionHistory:!1},skills:this.registry.list().map(h=>{let p=this.config.agents[h.id]||{},y=typeof p.description=="string"&&p.description.trim()||fI(p.systemPrompt)||`Agent "${h.name}" (${h.tier})`,b=Array.isArray(p.mentions)?p.mentions.slice(0,4):[];return{id:h.id,name:h.name,description:y,tags:[h.tier,...b],color:ce(h.id,p).color}}),channels:this.router.getChannelNames(),githubLogins:this.github?.postingAccounts()??[],defaultInputModes:["text"],defaultOutputModes:["text"]});break;case"GET /wiki/agents":{let h=this.registry.getWikiHub();this.json(t,200,{nodeId:this.config.node.id,agents:h.summary()});break}case"GET /wiki/entries":{let h=this.registry.getWikiHub(),p=n.searchParams.get("agent")||void 0,y=n.searchParams.get("after")||void 0,b=p?h.getAgentEntries(p):h.getSharedStore().listEntries({after:y});this.json(t,200,{nodeId:this.config.node.id,count:b.length,entries:b.map($=>({id:$.id,date:$.date,agentId:$.agentId,source:$.source,sourceContext:$.sourceContext,content:$.content}))});break}case"GET /wiki/articles":{let h=this.registry.getWikiHub(),p=n.searchParams.get("agent");if(!p){this.json(t,400,{error:"?agent= required"});break}let b=h.getAgentWiki(p).rebuildIndex();this.json(t,200,{nodeId:this.config.node.id,agentId:p,articles:b.articles});break}case"GET /wiki/article":{let h=this.registry.getWikiHub(),p=n.searchParams.get("agent"),y=n.searchParams.get("path");if(!p||!y){this.json(t,400,{error:"?agent= and ?path= required"});break}let $=h.getAgentWiki(p).readArticle(y);if(!$){this.json(t,404,{error:"Article not found"});break}this.json(t,200,{nodeId:this.config.node.id,agentId:p,path:$.path,title:$.meta.title,tags:$.meta.tags,owner:$.meta.owner,created:$.meta.created,lastUpdated:$.meta.lastUpdated,sources:$.meta.sources,content:$.content});break}case"GET /graph/schema":{let h=this.registry.getGraphStore();if(!h){this.json(t,404,{error:"graph disabled on this node"});break}this.json(t,200,{nodeId:this.config.node.id,schema:h.loadSchema()});break}case"GET /graph/nodes":{let h=this.registry.getGraphStore();if(!h){this.json(t,404,{error:"graph disabled on this node"});break}this.json(t,200,{nodeId:this.config.node.id,...h.loadNodes()});break}case"GET /graph/classifications":{let h=this.registry.getGraphStore();if(!h){this.json(t,404,{error:"graph disabled on this node"});break}let p=n.searchParams.get("status")||"approved",y=Math.max(1,Math.min(1e3,parseInt(n.searchParams.get("limit")||"200",10)||200)),b=h.listByStatus(p,y);this.json(t,200,{nodeId:this.config.node.id,status:p,count:b.length,classifications:b});break}default:this.json(t,404,{error:"Not found",endpoints:["GET /health","GET /agents","GET /crons","GET /routines \u2014 schedules + cron/hook workflows with staleness flags","GET /mesh","GET /wiki/agents","GET /wiki/entries[?agent=X&after=YYYY-MM-DD]","GET /wiki/articles?agent=X","GET /graph/schema","GET /graph/nodes","GET /graph/classifications[?status=approved|pending|rejected&limit=N]","POST /task { agent, message, context?, freshSession?: bool }","GET /agents/:id \u2014 resolved agent config (permission, tier, model, persistentProcess, toolUseRequired)","POST /agents/:id/selftest { message? } \u2014 canary probe; runs a fresh-session task and reports {ok, durationMs, tokens, billedModel}","GET /traces[?agentId=&channel=&chatId=&workflowRunId=&status=&since=&until=&limit=]","GET /traces/:taskId \u2014 full per-task execution trace (steps + tokens)","GET /voice/history[?agent=&limit=&before=] \u2014 past voice exchanges, bounded summaries","GET /voice/history/:id \u2014 one voice exchange in full; POST /voice/history/:id/replay","GET /api/processes \u2014 live persistent claude processes (JSON)","POST /api/processes/kill { agentId, channel, chatId, reason? }","GET /api/actions/builtin \u2014 list shipped built-in typed actions","POST /api/actions/builtin/:name \u2014 run a built-in with JSON body input","POST /mesh/task { peer, message }","POST /webhook/:agentId[/:source] \u2014 webhook callback","POST /reload \u2014 re-read agentx.json (hot-swaps crons)","GET /usage/plan \u2014 Claude plan windows, cold-dispatch counters, active holds","POST /usage/plan/lift \u2014 drop the active Claude plan holds","GET /daemon/restart \u2014 in-flight count, service manager, pending restart","POST /daemon/restart \u2014 restart when idle { timeoutMinutes?, onTimeout? }","POST /daemon/restart/cancel","GET /.well-known/agent-card.json","GET /call \u2014 browser UI for P2P A/V calls (requires channels.webrtc.enabled)","GET /webrtc/config \u2014 ICE servers + peer directory for the call page","GET /webrtc/events?callId=&as= \u2014 SSE stream of signaling events","POST /webrtc/signal/out \u2014 browser-originated signal, forwarded to remote peer","POST /webrtc/signal \u2014 remote-peer-originated signal, fanned out to local browser","POST /webrtc/bot/invite { callId, target, agentId } \u2014 spawn a transcribing bot peer for a call","GET /webrtc/bots \u2014 active bot sessions","POST /webrtc/camera/watch { callId, agentId } \u2014 an agent watches the phone camera share","GET /webrtc/camera/watch \u2014 agents watching a camera now","POST /webrtc/camera/watch/:id/look { note? } \u2014 ask the watching agent what it sees","POST /webrtc/camera/look { agentId } \u2014 from an agent's run: the newest frame as a PNG path"]})}}catch(i){this.json(t,500,{error:i.message})}}async handleOpenAICompat(e,t,n){let s=await U(e);await Eu(e,t,n,s,{execute:(i,o,a,c)=>this.registry.execute(i,o,a,c),agentIds:Object.keys(this.config.agents),cancel:(i,o,a,c)=>{let l=this.registry.list().find(d=>d.id===i)?.runningTasks.filter(d=>d.channel===o&&d.chatId===a)||[];for(let d of l)this.registry.cancelRunningTask(d.id,c)},log:i=>this.log(i)})}json(e,t,n){e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify(n,null,2))}resolveGitlabTokenForAgent(e){if(!e)return{token:this.config.channels.gitlab?.token,source:"global"};let t=(this.config.channels.gitlab?.agentMappings||[]).find(s=>s.agentId===e);if(t?.token)return{token:t.token,source:"agentMappings"};let n=Dg(this.config,e,"gitlab-user","tokenEnv");return n.status==="ok"&&n.value?{token:n.value,source:`integrations(${n.envVar})`}:this.config.channels.gitlab?.token?{token:this.config.channels.gitlab.token,source:"global"}:{token:void 0,source:n.status}}resolveTodayUsage(){let e=nh();if(e==="json")return this.registry.getTodayUsage();let t=th(this.db);return e==="sqlite"||Object.keys(t.agents).length>0?t:this.registry.getTodayUsage()}installAgentMemorySurface(){let e=parseInt(this.config.node.bind.split(":")[1]||"18800",10);for(let t of this.registry.list()){let n=t.workspace;if(!(!n||!vt(n)))try{let s=Q(n,".claude","skills");yf(s,{recursive:!0});let i=Q(s,Gg);if(!vt(i))Uo(i,Gi(e)),this.log(` memory-skill: installed remember.md \u2192 ${t.id}`);else{let o=Bg(tn(i,"utf-8"),e);o&&(Uo(i,o),this.log(` memory-skill: updated remember.md \u2192 ${t.id}`))}this.agentMemory.syncToWorkspace(t.id,n)}catch(s){this.log(` memory-skill: ${t.id} install failed \u2014 ${s?.message??s}`)}}}installAgentMcpConfig(){for(let[e,t]of Object.entries(this.config.agents)){let n=t.workspace;if(!n||!vt(n))continue;let s=Fg(Sa(t),this.config.requests.enabled?Lg():null);try{switch(Ug(n,s)){case"installed":this.log(` mcp: installed ${Object.keys(s).length} server(s) \u2192 ${e}`);break;case"updated":this.log(` mcp: updated .mcp.json (${Object.keys(s).length} server(s)) \u2192 ${e}`);break;case"removed":this.log(` mcp: removed managed .mcp.json (config now empty) \u2192 ${e}`);break;case"skipped-operator-owned":Object.keys(s).length>0&&this.log(` mcp: ${e} has operator-owned .mcp.json \u2014 skipping (delete file or marker to let agentx manage)`);break;case"noop":break}}catch(i){this.log(` mcp: ${e} install failed \u2014 ${i?.message??i}`)}}}workspaceFor(e){for(let t of this.registry.list())if(t.id===e)return t.workspace;return null}handleMemoryApi(e,t,n,s){return pg(e,t,n,s,{mem:this.agentMemory,workspaceFor:i=>this.workspaceFor(i),runningTaskOwner:i=>this.registry.runningTaskOwner(i)})}async handleWorkflowEvent(e,t){if(!this.workflowDispatcher){this.json(t,503,{error:"workflow engine not enabled on this node"});return}let n;try{n=await te(e)}catch(c){this.json(t,400,{error:"invalid JSON body",message:c.message});return}let s=n?.payload??n,i=s?.event,o=s?.entityRef;if(!i?.id||!o?.backend||!o?.id){this.json(t,400,{error:"missing event or entityRef"});return}let a=n?.kind;try{if(a==="trigger"&&s.trigger){let g=typeof n?.fromPeer=="string"?n.fromPeer:"unknown";this.log(`[workflows/mesh] received trigger from "${g}" source="${s.trigger.source}" chat="${s.trigger.chat??"*"}"`);let m=await this.workflowDispatcher.dispatch({trigger:s.trigger,entityRef:o,event:i,fromRemote:{peer:g}});this.log(`[workflows/mesh] dispatched broadcast: matched=${m.claimed.length} ${m.claimed.length?`(${m.claimed.map(f=>f.id).join(", ")})`:"[none \u2014 no workflow with mesh.allowRemote matched]"}`),this.json(t,202,{ok:!0,mode:"trigger-broadcast",matched:m.claimed.map(f=>f.id)});return}let d=(s.workflowId?this.workflowStore?.get(s.workflowId):null)?.nodes.find(g=>g.type.startsWith("trigger."))?.config??{},u={source:String(d.source??"hook"),project:d.filter?.project,repo:d.filter?.repo,chat:d.filter?.chat,labels:d.filter?.labels};await this.workflowDispatcher.dispatch({trigger:u,entityRef:o,event:i}),this.json(t,202,{ok:!0})}catch(c){this.log(`[workflows] /workflow/event failed: ${c.message}`),this.json(t,500,{error:c.message})}}async relayPush(e,t){let n=e.toLowerCase(),s=this.mesh?.directory().find(a=>a.peer.toLowerCase()===n);if(!s)throw new Error(`push: channels.push.relayTo "${e}" is not a mesh peer of this node`);let i=await fetch(`${s.peerUrl}/channel/send`,{method:"POST",headers:{"Content-Type":"application/json",...this.mesh.authHeaders(s.peer)},body:JSON.stringify(t),signal:AbortSignal.timeout(15e3)});if(!i.ok)throw new Error(`push: ${s.peer} /channel/send -> ${i.status} ${(await i.text().catch(()=>"")).slice(0,200)}`);return(await i.json().catch(()=>({}))).messageId??void 0}async handleChannelSend(e,t){let n;try{n=await te(e)}catch(c){this.json(t,400,{error:"invalid JSON body",message:c.message});return}let s=String(n?.channel??""),i=String(n?.chatId??""),o=String(n?.text??"");if(!s||!i||!o){this.json(t,400,{error:"channel, chatId, and text are required"});return}if(!this.router.getChannel(s)){this.json(t,404,{error:`channel "${s}" not hosted on this node`});return}try{let c=await this.router.sendOutbound({channel:s,chatId:i,text:o,accountId:typeof n.accountId=="string"?n.accountId:void 0,parseMode:typeof n.parseMode=="string"?n.parseMode:void 0,replyTo:typeof n.replyTo=="string"?n.replyTo:void 0,buttons:Array.isArray(n.buttons)?n.buttons:void 0,agentId:typeof n.agentId=="string"?n.agentId:void 0,relayed:n.relayed===!0?!0:void 0},{recordInSession:!1});this.json(t,200,{ok:!0,messageId:c??null})}catch(c){this.log(`[mesh] /channel/send "${s}" failed: ${c.message}`),this.json(t,500,{error:c.message})}}async handleChannelChats(e,t,n={}){let s=new Set,i=[],o=[],a=(l,d)=>{let u=0;for(let g of l)!g.id||s.has(g.id)||(s.add(g.id),i.push({...g,source:d}),u++);u>0&&o.push(`${d}:${u}`)},c=this.router.getChannel(t);if(c?.listKnownChats)try{a(c.listKnownChats(),"local")}catch{}else if(c?.listChats)try{a(c.listChats().map(l=>({id:l.jid,name:l.name,kind:l.isGroup?"group":"dm"})),"local")}catch{}if(!n.localOnly&&this.mesh){let l=this.mesh.directory().filter(d=>d.healthy&&d.channels?.includes(t));await Promise.allSettled(l.map(async d=>{try{let u=await fetch(`${d.peerUrl}/channels/${encodeURIComponent(t)}/chats?local=1`,{headers:this.mesh.authHeaders(d.peer),signal:AbortSignal.timeout(5e3)});if(!u.ok)return;let g=await u.json();Array.isArray(g.chats)&&a(g.chats.map(m=>({id:m.id,name:m.name,kind:m.kind??"dm",accountId:m.accountId})),`mesh:${d.peer}`)}catch{}}))}this.json(e,200,{channel:t,source:o.join(", ")||"none",chats:i})}async handleWorkflowManualRun(e,t,n){if(!this.workflowDispatcher||!this.workflowStore){this.json(t,503,{error:"workflow engine not enabled on this node"});return}let s;try{s=await te(e)}catch{s={}}try{let i=await Og({get:o=>this.workflowStore.get(o),dispatchWorkflow:o=>this.workflowDispatcher.dispatchWorkflow(o)},n,s);this.json(t,i.status,i.body)}catch(i){this.log(`[workflows] manual run "${n}" failed: ${i.message}`),this.json(t,500,{error:i.message})}}},Go=Ho;Ke(Go,"MESH_PROTECTED_PATHS",new Set(["/task","/ask","/mesh/task","/mesh/inbox/send","/workflow/event","/workflow/transition","/channel/send","/webrtc/signal","/gitlab/react","/gitlab/send-note","/gitlab/log-time","/channel/edit-comment","/github/send-comment"]));function fI(r){if(typeof r!="string")return"";let e=r.trim();if(!e)return"";let t=e.match(/^[^.!?\n]+[.!?]?/),n=(t?t[0]:e).trim();return n.length>140?n.slice(0,137)+"\u2026":n}function te(r){return new Promise((e,t)=>{let n="";r.setEncoding("utf8"),r.on("data",s=>{n+=s}),r.on("end",()=>{try{e(n?JSON.parse(n):{})}catch(s){t(s)}}),r.on("error",t)})}function yI(r,e){let t=["model","workspace","tier","permissionMode","mcpServers"],n=new Set,s=new Set([...Object.keys(r),...Object.keys(e)]);for(let i of s){let o=r[i],a=e[i];if(!o||!a){n.add("add/remove");continue}for(let c of t)JSON.stringify(o[c])!==JSON.stringify(a[c])&&n.add(`${i}.${c}`)}return Array.from(n).slice(0,6)}async function U(r){return new Promise((e,t)=>{let n="";r.on("data",s=>n+=s.toString()),r.on("end",()=>{try{e(n?JSON.parse(n):{})}catch{e({})}}),r.on("error",t)})}kf();function cj(r){typeof r=="string"&&(nn.error(r),process.exit(1)),r instanceof Error&&(nn.error(r.message),process.exit(1)),nn.error("Something went wrong. Please try again."),process.exit(1)}export{EI as a,Gr as b,He as c,Et as d,Mt as e,Ve as f,_n as g,zd as h,qu as i,ib as j,ob as k,zu as l,Ee as m,ut as n,Zu as o,ht as p,mA as q,fA as r,bk as s,Oi as t,eE as u,tE as v,nE as w,Ig as x,Yk as y,aE as z,cE as A,ps as B,Gt as C,rp as D,Kv as E,EC as F,ws as G,to as H,no as I,Is as J,ce as K,qp as L,Ts as M,NS as N,sm as O,jS as P,am as Q,Rs as R,Kt as S,Ms as T,Os as U,gm as V,yo as W,Me as X,ye as Y,vm as Z,Sm as _,Im as $,$m as aa,Zs as ba,cf as ca,jo as da,df as ea,rI as fa,q_ as ga,Go as ha,cj as ia};
1141
- //# sourceMappingURL=chunk-TYK6LAAG.js.map
1141
+ //# sourceMappingURL=chunk-2X5RPHPN.js.map