agentix-cli 0.92.4 → 0.93.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.
@@ -18,6 +18,9 @@ final class CharacterHost {
18
18
  private static let size = NSSize(width: 440, height: 150)
19
19
  /// The edge it hovers above, from the bottom of its window.
20
20
  private static let ground: CGFloat = 8
21
+ /// Above the edge, clear of its body at the top of a hop: where its
22
+ /// speech bubble's tail ends.
23
+ private static let head: CGFloat = 78
21
24
 
22
25
  private let window: NSPanel
23
26
  private let view = CharacterView(frame: NSRect(origin: .zero, size: CharacterHost.size))
@@ -34,6 +37,11 @@ final class CharacterHost {
34
37
  var levelSource: (() -> Float)?
35
38
  /// Where the pointer is, in screen coordinates.
36
39
  var pointerSource: () -> NSPoint = { NSEvent.mouseLocation }
40
+ /// Its speech bubble (#491), the pill: told every frame where the
41
+ /// character's head is and on which screen, it answers with where the
42
+ /// bubble is, or nil while it is hidden. Set by the app.
43
+ var bubble: ((NSPoint, NSRect) -> NSRect?)?
44
+ private var bubbleFrame: NSRect?
37
45
 
38
46
  init() {
39
47
  window = NSPanel(contentRect: NSRect(origin: .zero, size: Self.size),
@@ -79,6 +87,12 @@ final class CharacterHost {
79
87
  func show(_ activity: CharacterMath.Activity, tint: NSColor, colors: [NSColor]?) {
80
88
  self.activity = activity
81
89
  view.stops = CharacterDraw.stops(tint: tint, colors: colors)
90
+ redraw()
91
+ }
92
+
93
+ /// Standing still, it is drawn again when something changes: its
94
+ /// state, or its bubble showing or hiding.
95
+ func redraw() {
82
96
  if shown && timer == nil { tick() }
83
97
  }
84
98
 
@@ -101,10 +115,10 @@ final class CharacterHost {
101
115
  // The screen with the menu bar, less the menu bar and the Dock.
102
116
  guard let screen = NSScreen.screens.first else { return }
103
117
  let visible = screen.visibleFrame
104
- // It rests beside the pill's own corner, so they read as one, and
105
- // goes no further right: stepping aside never puts it on the pill.
118
+ // It rests under the right end of its bubble, the bubble in the
119
+ // pill's own corner, and goes no further right.
106
120
  let left = Double(visible.minX + 44)
107
- let home = max(Double(visible.maxX - PillPlacement.inset - Panel.size.width - 52), left)
121
+ let home = max(Double(visible.maxX - PillPlacement.inset - PillPlacement.bubbleReach), left)
108
122
  let range = left...home
109
123
 
110
124
  let frame: CharacterSim.Frame
@@ -118,11 +132,18 @@ final class CharacterHost {
118
132
  }
119
133
  let mouse = pointerSource()
120
134
  let pointer = screen.frame.contains(mouse) ? (x: Double(mouse.x), y: Double(mouse.y - visible.minY)) : nil
135
+ // The gap its tail fills counts as the bubble, so a pointer a
136
+ // little under a button does not send both away.
137
+ let held = bubbleFrame?.insetBy(dx: 0, dy: -PillPlacement.tail).contains(mouse) ?? false
121
138
  frame = sim.step(to: ProcessInfo.processInfo.systemUptime,
122
- CharacterSim.Input(activity: activity, level: level, pointer: pointer, home: home, range: range))
139
+ CharacterSim.Input(activity: activity, level: level, pointer: pointer, held: held,
140
+ home: home, range: range))
123
141
  }
124
142
  let origin = NSPoint(x: (CGFloat(frame.x) - Self.size.width / 2).rounded(), y: visible.minY - Self.ground)
125
143
  if window.frame.origin != origin { window.setFrameOrigin(origin) }
144
+ // The bubble goes with the window, so the two move as one.
145
+ bubbleFrame = bubble?(NSPoint(x: origin.x + Self.size.width / 2, y: visible.minY + Self.head), visible)
146
+ view.bubble = bubbleFrame?.offsetBy(dx: -origin.x, dy: -origin.y)
126
147
  view.origin = origin.x
127
148
  view.shown = frame
128
149
  view.needsDisplay = true
@@ -138,6 +159,8 @@ final class CharacterView: NSView {
138
159
  /// Under the character, in this view; and the view's left edge on screen.
139
160
  var edge = CGPoint.zero
140
161
  var origin: CGFloat = 0
162
+ /// Its speech bubble in this window, origin bottom-left; nil while hidden.
163
+ var bubble: NSRect?
141
164
 
142
165
  override var isFlipped: Bool { true }
143
166
  override func hitTest(_ point: NSPoint) -> NSView? { nil }
@@ -148,5 +171,30 @@ final class CharacterView: NSView {
148
171
  // to the nearest point; the rest of the way is drawn here.
149
172
  let at = CGPoint(x: CGFloat(shown.x) - origin, y: edge.y)
150
173
  CharacterDraw.draw(shown, in: ctx, edge: at, origin: origin, unit: unit, stops: stops)
174
+ if let bubble { drawTail(in: ctx, from: bubble) }
175
+ }
176
+
177
+ /// The bubble's tail: a small point from its bottom edge down to the
178
+ /// character, in the bubble's own colours.
179
+ private func drawTail(in ctx: CGContext, from bubble: NSRect) {
180
+ let half: CGFloat = 7, corner = Brand.Radius.lg + half
181
+ let x = min(max(bounds.midX, bubble.minX + corner), bubble.maxX - corner)
182
+ // One point up into the bubble, so no gap shows between the two.
183
+ let top = bounds.height - bubble.minY - 1
184
+ let tip = CGPoint(x: x, y: top + 1 + PillPlacement.tail)
185
+ effectiveAppearance.performAsCurrentDrawingAppearance {
186
+ ctx.move(to: CGPoint(x: x - half, y: top))
187
+ ctx.addLine(to: tip)
188
+ ctx.addLine(to: CGPoint(x: x + half, y: top))
189
+ ctx.closePath()
190
+ ctx.setFillColor(NSColor.windowBackgroundColor.withAlphaComponent(0.92).cgColor)
191
+ ctx.fillPath()
192
+ ctx.move(to: CGPoint(x: x - half, y: top + 1))
193
+ ctx.addLine(to: tip)
194
+ ctx.addLine(to: CGPoint(x: x + half, y: top + 1))
195
+ ctx.setStrokeColor(NSColor.separatorColor.cgColor)
196
+ ctx.setLineWidth(1)
197
+ ctx.strokePath()
198
+ }
151
199
  }
152
200
  }
@@ -17,6 +17,9 @@ struct CharacterSim {
17
17
  /// The pointer: along the edge, and its height above it. Nil when
18
18
  /// it is on another screen.
19
19
  var pointer: (x: Double, y: Double)?
20
+ /// The pointer is on its speech bubble: it stays where it is, so
21
+ /// the bubble is not pulled from under the pointer.
22
+ var held = false
20
23
  /// Where it rests, and how far it may go.
21
24
  var home = 0.0
22
25
  var range: ClosedRange<Double> = 0...0
@@ -99,7 +102,10 @@ struct CharacterSim {
99
102
  // The pointer comes close: out of its way. Left alone: back home,
100
103
  // unless the pointer is resting there.
101
104
  let near = input.pointer.map { abs($0.x - x) < reach && $0.y < tall } ?? false
102
- if near {
105
+ if input.held {
106
+ target = x
107
+ awayUntil = max(awayUntil, now + Self.awayFor)
108
+ } else if near {
103
109
  target = M.aside(x: x, pointer: input.pointer!.x, clear: Self.clear, range: input.range)
104
110
  awayUntil = now + Self.awayFor
105
111
  restSince = now
@@ -107,11 +107,18 @@ final class Panel: NSPanel {
107
107
 
108
108
  /// Told what the orb is shown, so the character can show the same.
109
109
  var onLook: ((State, NSColor, [NSColor]?) -> Void)?
110
+ /// Told when it comes on screen or leaves it, so a still character
111
+ /// draws its bubble's tail again.
112
+ var onShown: (() -> Void)?
110
113
 
111
114
  /// Off while the character stands in for the orb (Character.swift):
112
115
  /// the words start where the orb was.
113
116
  private(set) var showsOrb = true
114
117
 
118
+ /// Set while the pill is the character's speech bubble: where the
119
+ /// character's head is, and the screen it is on.
120
+ private(set) var bubble: (head: NSPoint, visible: NSRect)?
121
+
115
122
  /// Told of every state rendered, so the menu-bar icon can follow.
116
123
  var onRender: ((State) -> Void)?
117
124
 
@@ -332,18 +339,50 @@ final class Panel: NSPanel {
332
339
  @MainActor
333
340
  func restorePosition() {
334
341
  collapse(animated: false)
342
+ if let bubble {
343
+ place(PillPlacement.bubble(size: frame.size, head: bubble.head, visible: bubble.visible))
344
+ return
345
+ }
335
346
  let screens = NSScreen.screens.map(\.visibleFrame)
336
347
  let fallback = (NSScreen.main ?? NSScreen.screens.first)?.visibleFrame ?? .zero
337
348
  place(PillPlacement.clamp(saved: Config.pillOrigin, size: frame.size, screens: screens, fallback: fallback))
338
349
  }
339
350
 
340
351
  /// Back to the bottom-right corner, forgetting where it was dragged.
352
+ /// Not while it is the character's bubble: nothing would move, and
353
+ /// the place kept for the orb look would be lost.
341
354
  @MainActor
342
355
  func resetPosition() {
356
+ guard bubble == nil else { return }
343
357
  Config.pillOrigin = nil
344
358
  restorePosition()
345
359
  }
346
360
 
361
+ /// The character's speech bubble (#491): the pill sits above `head`,
362
+ /// the top of the character, and goes where it goes, grown or not. It
363
+ /// is not dragged by itself, and the place it was dragged to as a
364
+ /// pill is kept for the orb look.
365
+ @MainActor
366
+ func attach(head: NSPoint, visible: NSRect) {
367
+ bubble = (head, visible)
368
+ isMovableByWindowBackground = false
369
+ // Growing or collapsing: it catches up on the next frame.
370
+ guard placing == 0 else { return }
371
+ let to = PillPlacement.bubble(size: Self.size, head: head, visible: visible)
372
+ let from = collapsedFrame().origin
373
+ let moved = PillPlacement.inside(frame.offsetBy(dx: to.x - from.x, dy: to.y - from.y), visible)
374
+ if moved.origin != frame.origin { place(moved.origin) }
375
+ }
376
+
377
+ /// The orb look again: a pill of its own, back where it was left.
378
+ @MainActor
379
+ func detach() {
380
+ guard bubble != nil else { return }
381
+ bubble = nil
382
+ isMovableByWindowBackground = true
383
+ restorePosition()
384
+ }
385
+
347
386
  @MainActor
348
387
  private func place(_ origin: NSPoint) {
349
388
  placing += 1
@@ -398,7 +437,7 @@ final class Panel: NSPanel {
398
437
  func show() {
399
438
  orb.setOnScreen(showsOrb)
400
439
  miniOrbs.setOnScreen(!miniOrbs.isHidden)
401
- if !isVisible { orderFrontRegardless() }
440
+ if !isVisible { orderFrontRegardless(); onShown?() }
402
441
  }
403
442
 
404
443
  @MainActor
@@ -406,7 +445,7 @@ final class Panel: NSPanel {
406
445
  closeButton.isHidden = true
407
446
  orb.setOnScreen(false)
408
447
  miniOrbs.setOnScreen(false)
409
- if isVisible { orderOut(nil) }
448
+ if isVisible { orderOut(nil); onShown?() }
410
449
  }
411
450
 
412
451
  @objc private func closeClicked() { onDismiss?() }
@@ -461,7 +500,6 @@ final class Panel: NSPanel {
461
500
  default: colors = agentPalette()
462
501
  }
463
502
  orb.show(state.orbPhase, tint: tint, colors: colors)
464
- onLook?(state, tint, colors)
465
503
 
466
504
  if state.isMeta {
467
505
  stopMarquee()
@@ -477,6 +515,9 @@ final class Panel: NSPanel {
477
515
  // Grown into an answer, it stays until it collapses, idle or not;
478
516
  // so does a pill with agents still busy in its mini orbs.
479
517
  if dismissed || (state.isMeta && !alwaysVisible && !expanded && busyCount == 0) { hide() } else { show() }
518
+ // After showing or hiding: a still character draws its bubble's
519
+ // tail only while the bubble is on screen.
520
+ onLook?(state, tint, colors)
480
521
  armCollapse()
481
522
  onRender?(state)
482
523
  }
@@ -68,6 +68,18 @@ enum PillPlacement {
68
68
  width: size.width, height: size.height)
69
69
  }
70
70
 
71
+ /// How far the bubble reaches to the right of the character's middle,
72
+ /// and the gap above its head that the bubble's tail fills.
73
+ static let bubbleReach: CGFloat = 64
74
+ static let tail: CGFloat = 10
75
+
76
+ /// The pill as the character's speech bubble (#491): above `head`,
77
+ /// the top of the character, most of it to the left, kept on screen.
78
+ static func bubble(size: CGSize, head: CGPoint, visible: CGRect) -> CGPoint {
79
+ inside(CGRect(x: head.x + bubbleReach - size.width, y: head.y + tail,
80
+ width: size.width, height: size.height), visible).origin
81
+ }
82
+
71
83
  /// `frame` moved the least distance that puts it inside `bounds`. A
72
84
  /// frame larger than `bounds` keeps its top-left corner in view.
73
85
  static func inside(_ frame: CGRect, _ bounds: CGRect) -> CGRect {
@@ -204,6 +204,7 @@ final class App: NSObject, NSApplicationDelegate {
204
204
  let asCharacter = saved.general.look == "character"
205
205
  panel.setShowsOrb(!asCharacter)
206
206
  character.setShown(asCharacter)
207
+ if !asCharacter { panel.detach() }
207
208
  if settingsWindow.model.recording == nil { registerHotkeys() }
208
209
  // Colours may have changed.
209
210
  statusMenu.refresh()
@@ -314,9 +315,17 @@ final class App: NSObject, NSApplicationDelegate {
314
315
  panel.orb.levelSource = { [weak self] in self?.recorder.level ?? 0 }
315
316
  character.setAnimated(Config.animatedOrb)
316
317
  character.levelSource = { [weak self] in self?.recorder.level ?? 0 }
318
+ // The pill is the character's speech bubble: it goes where the
319
+ // character goes.
320
+ character.bubble = { [weak self] head, visible in
321
+ guard let panel = self?.panel else { return nil }
322
+ panel.attach(head: head, visible: visible)
323
+ return panel.isVisible ? panel.frame : nil
324
+ }
317
325
  panel.onLook = { [weak self] state, tint, colors in
318
326
  self?.character.show(state.activity, tint: tint, colors: colors)
319
327
  }
328
+ panel.onShown = { [weak self] in self?.character.redraw() }
320
329
  panel.onDismiss = { [weak self] in self?.dismissPill() }
321
330
  panel.agentPalette = { [weak self] in
322
331
  guard let self else { return nil }
@@ -512,7 +512,7 @@ ${l}`)}let S={agentId:o,message:v,context:{channel:y,sender:f?"opencode":"openai
512
512
 
513
513
  `)}}function yu(r){r.writeHead(200,{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache",Connection:"keep-alive","X-Accel-Buffering":"no"})}function wu(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 bu(r,e,t,n,s,i){let o=i?.usage?.inputTokens??0,a=i?.usage?.outputTokens??Math.ceil(s.length/4);ri(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 ri(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;Xe(Nt,"levelOrder",{debug:0,info:1,warn:2,error:3});import{realpathSync as xw,statSync as Aw}from"fs";var lt={version:"0.92.4",commit:"8dc47ce",startedAt:new Date(Date.now()-process.uptime()*1e3).toISOString()};function Rw(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 vu(){let r=null;try{r=Aw(xw(process.argv[1])).mtimeMs}catch{}let e=Hd().version;return Rw(lt,{mtimeMs:r,version:e&&e!=="0.0.0"?e:null})}import{randomUUID as Ew}from"crypto";var qn=class{constructor(e=new Ra){this.core=e}count=0;subscribe(e,t){this.count++;let n=this.core.subscribe((i,o)=>{if(!o||!Cw.includes(o.kind))return;let a={...o,rootId:i.rootId,node:i.node};Mw(e,a)&&t(a)}),s=!0;return()=>{s&&(s=!1,this.count--,n())}}publish(e){let t={id:typeof e.id=="string"?e.id:Ew(),at:typeof e.at=="string"?e.at:new Date().toISOString(),...e},{type:n,summary:s,ref:i,agentId:o}=Pw(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}},Cw=["run","task","signal","mesh","channel","status"];function Pw(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 Mw(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 Su(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 Vn,timingSafeEqual as Iu}from"crypto";var Jn=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 h=this.extractEventType(l,c,e.headers),m=this.webhookEntries.find(k=>k.enabled&&k.agentId===i&&k.source===l),f=h&&m?.triggers?.[h]||m?.defaultWorkflow||null;if(await this.fireHookSafe(l,h,i,c),f&&this.workflowDispatcher)try{let k=await this.workflowDispatcher.dispatchWorkflow({workflowId:f,entityRef:{kind:"webhook",id:`${l}:${i}:${h??"\u2014"}:${Date.now()}`},event:{kind:"webhook",source:l,eventType:h,payload:c},trigger:{source:l}});this.log(`Webhook [${l}/${h??"\u2014"}] -> workflow=${f} (claimed=${k.claimed})`),this.sendJson(t,202,{ok:!0,agent:i,source:l,eventType:h,workflow:f,claimed:k.claimed});return}catch(k){this.log(`Workflow dispatch failed [${l}/${h}/${f}]: ${k.message}`)}let y=this.webhookEntries.find(k=>k.enabled&&k.node&&k.agentId===i&&k.source===l);if(y?.node&&this.mesh){this.sendJson(t,202,{ok:!0,agent:i,source:l,node:y.node,status:"accepted"}),this.mesh.sendTask(y.node,u,i,{context:{channel:`webhook:${l}`,sender:`webhook:${l}`}}).then(k=>this.log(`Mesh-forwarded webhook [${l}] -> ${y.node}/${i}: ${k?.slice(0,100)||"ok"}`),k=>this.log(`Mesh forward failed [${l}] -> ${y.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 bu(r,e,t,n,s,i){let o=i?.usage?.inputTokens??0,a=i?.usage?.outputTokens??Math.ceil(s.length/4);ri(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 ri(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;Xe(Nt,"levelOrder",{debug:0,info:1,warn:2,error:3});import{realpathSync as xw,statSync as Aw}from"fs";var lt={version:"0.93.0",commit:"aa0e61a",startedAt:new Date(Date.now()-process.uptime()*1e3).toISOString()};function Rw(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 vu(){let r=null;try{r=Aw(xw(process.argv[1])).mtimeMs}catch{}let e=Hd().version;return Rw(lt,{mtimeMs:r,version:e&&e!=="0.0.0"?e:null})}import{randomUUID as Ew}from"crypto";var qn=class{constructor(e=new Ra){this.core=e}count=0;subscribe(e,t){this.count++;let n=this.core.subscribe((i,o)=>{if(!o||!Cw.includes(o.kind))return;let a={...o,rootId:i.rootId,node:i.node};Mw(e,a)&&t(a)}),s=!0;return()=>{s&&(s=!1,this.count--,n())}}publish(e){let t={id:typeof e.id=="string"?e.id:Ew(),at:typeof e.at=="string"?e.at:new Date().toISOString(),...e},{type:n,summary:s,ref:i,agentId:o}=Pw(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}},Cw=["run","task","signal","mesh","channel","status"];function Pw(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 Mw(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 Su(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 Vn,timingSafeEqual as Iu}from"crypto";var Jn=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 h=this.extractEventType(l,c,e.headers),m=this.webhookEntries.find(k=>k.enabled&&k.agentId===i&&k.source===l),f=h&&m?.triggers?.[h]||m?.defaultWorkflow||null;if(await this.fireHookSafe(l,h,i,c),f&&this.workflowDispatcher)try{let k=await this.workflowDispatcher.dispatchWorkflow({workflowId:f,entityRef:{kind:"webhook",id:`${l}:${i}:${h??"\u2014"}:${Date.now()}`},event:{kind:"webhook",source:l,eventType:h,payload:c},trigger:{source:l}});this.log(`Webhook [${l}/${h??"\u2014"}] -> workflow=${f} (claimed=${k.claimed})`),this.sendJson(t,202,{ok:!0,agent:i,source:l,eventType:h,workflow:f,claimed:k.claimed});return}catch(k){this.log(`Workflow dispatch failed [${l}/${h}/${f}]: ${k.message}`)}let y=this.webhookEntries.find(k=>k.enabled&&k.node&&k.agentId===i&&k.source===l);if(y?.node&&this.mesh){this.sendJson(t,202,{ok:!0,agent:i,source:l,node:y.node,status:"accepted"}),this.mesh.sendTask(y.node,u,i,{context:{channel:`webhook:${l}`,sender:`webhook:${l}`}}).then(k=>this.log(`Mesh-forwarded webhook [${l}] -> ${y.node}/${i}: ${k?.slice(0,100)||"ok"}`),k=>this.log(`Mesh forward failed [${l}] -> ${y.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??"?",h=l.changeFlag??l.changeSource??"";s.push(` - ${d} (object ${u}${h?`, ${h}`:""})`)}}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="+Vn("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 h=Vn("sha256",a).update(`${u.t}.${t}`).digest("hex");return dt(h,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 h=parseInt(u,10);if(!Number.isFinite(h))return"malformed X-HubSpot-Request-Timestamp";let m=Date.now()-h;if(m>5*6e4)return`HubSpot webhook is ${Math.floor(m/1e3)}s old (>5min replay window)`;let f="POST",y=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&&y&&I.add(`${S}://${k}${y}`),v&&y&&I.add(`https://${v}${y}`),v&&y&&I.add(`http://${v}${y}`),y&&I.add(y),I.add("");for(let A of I){let D=Vn("sha256",a).update(`${f}${A}${t}${u}`).digest("base64");if(d.length===D.length&&Iu(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 h=Vn("sha256",a).update(t).digest("hex"),m=d.startsWith("sha256=")?d.slice(7):d;return dt(h,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 Iu(t,n)?null:"signature mismatch"}gf();cf();function _w(r){return{insertTaskHistory:r.prepare(`
@@ -1137,4 +1137,4 @@ data: ${JSON.stringify(W)}
1137
1137
  `)}catch{}},O=setInterval(()=>{try{t.write(`: ping
1138
1138
 
1139
1139
  `)}catch{}},15e3);O.unref?.();let j=new AbortController;t.on("close",()=>{t.writableEnded||j.abort()});try{for await(let N of this.mesh.sendTaskStream(g.peer,g.message,g.agent,{context:g.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=g.context,P=typeof g.senderAgentId=="string"?g.senderAgentId:void 0;if(jm(g,!0)==="callback"){let x=this.delegationGate(e,g,{callee:g.agent,peer:g.peer,message:g.message,calleeContext:M});if(!("track"in x)){let O=Fs(x);this.json(t,O.status,O.body);break}}if(g.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=g.peer,W=g.agent,z=this.mesh;(async()=>{let B=Date.now(),H;try{H=await z.sendTask(N,g.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(g.peer,g.message,g.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 w=await this.webrtc.handleOutgoing(p);this.json(t,w.ok?200:400,w);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 w=this.webrtc.handleIncoming(p);this.json(t,w.ok?200:400,w);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 g=await U(e),p=g.callId,w=g.target,b=g.agentId||this.config.channels.webrtc?.bot.defaultAgentId;if(!p||!w||!b){this.json(t,400,{error:"Missing: callId, target, agentId (or defaultAgentId in config)"});return}let $=await this.botManager.invite({callId:p,target:w,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 g=this.config.channels.webrtc;if(!g?.enabled){this.json(t,404,{error:"WebRTC signaling not enabled"});return}this.json(t,200,{localName:this.config.node.name,iceServers:[...g.stunServers.map(p=>({urls:p})),...g.turnServers],peers:this.mesh?.directory().map(p=>({name:p.peer,healthy:p.healthy}))||[],camera:g.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(g=>{let p=this.config.agents[g.id]||{},w=typeof p.description=="string"&&p.description.trim()||tI(p.systemPrompt)||`Agent "${g.name}" (${g.tier})`,b=Array.isArray(p.mentions)?p.mentions.slice(0,4):[];return{id:g.id,name:g.name,description:w,tags:[g.tier,...b],color:re(g.id,p).color}}),channels:this.router.getChannelNames(),defaultInputModes:["text"],defaultOutputModes:["text"]});break;case"GET /wiki/agents":{let g=this.registry.getWikiHub();this.json(t,200,{nodeId:this.config.node.id,agents:g.summary()});break}case"GET /wiki/entries":{let g=this.registry.getWikiHub(),p=n.searchParams.get("agent")||void 0,w=n.searchParams.get("after")||void 0,b=p?g.getAgentEntries(p):g.getSharedStore().listEntries({after:w});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 g=this.registry.getWikiHub(),p=n.searchParams.get("agent");if(!p){this.json(t,400,{error:"?agent= required"});break}let b=g.getAgentWiki(p).rebuildIndex();this.json(t,200,{nodeId:this.config.node.id,agentId:p,articles:b.articles});break}case"GET /wiki/article":{let g=this.registry.getWikiHub(),p=n.searchParams.get("agent"),w=n.searchParams.get("path");if(!p||!w){this.json(t,400,{error:"?agent= and ?path= required"});break}let $=g.getAgentWiki(p).readArticle(w);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 g=this.registry.getGraphStore();if(!g){this.json(t,404,{error:"graph disabled on this node"});break}this.json(t,200,{nodeId:this.config.node.id,schema:g.loadSchema()});break}case"GET /graph/nodes":{let g=this.registry.getGraphStore();if(!g){this.json(t,404,{error:"graph disabled on this node"});break}this.json(t,200,{nodeId:this.config.node.id,...g.loadNodes()});break}case"GET /graph/classifications":{let g=this.registry.getGraphStore();if(!g){this.json(t,404,{error:"graph disabled on this node"});break}let p=n.searchParams.get("status")||"approved",w=Math.max(1,Math.min(1e3,parseInt(n.searchParams.get("limit")||"200",10)||200)),b=g.listByStatus(p,w);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 ku(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=xg(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=Ju();if(e==="json")return this.registry.getTodayUsage();let t=Vu(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");sf(s,{recursive:!0});let i=Q(s,Mg);if(!vt(i))Po(i,Oi(e)),this.log(` memory-skill: installed remember.md \u2192 ${t.id}`);else{let o=Og(Zt(i,"utf-8"),e);o&&(Po(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=Cg(pa(t),this.config.requests.enabled?Eg():null);try{switch(Pg(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 ig(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 h=typeof n?.fromPeer=="string"?n.fromPeer:"unknown";this.log(`[workflows/mesh] received trigger from "${h}" source="${s.trigger.source}" chat="${s.trigger.chat??"*"}"`);let m=await this.workflowDispatcher.dispatch({trigger:s.trigger,entityRef:o,event:i,fromRemote:{peer:h}});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(h=>h.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 h of l)!h.id||s.has(h.id)||(s.add(h.id),i.push({...h,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 h=await u.json();Array.isArray(h.chats)&&a(h.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 Tg({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})}}},Mo=_o;Xe(Mo,"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 tI(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 nI(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)})}af();function jN(r){typeof r=="string"&&(en.error(r),process.exit(1)),r instanceof Error&&(en.error(r.message),process.exit(1)),en.error("Something went wrong. Please try again."),process.exit(1)}export{pI as a,Or as b,Ge as c,Et as d,Mt as e,qe as f,Cn as g,Hd as h,Nu as i,Bw as j,Ww as k,Gu as l,Ce as m,ut as n,Wu as o,ht as p,Yx as q,Qx as r,sk as s,Ai as t,NR as u,jR as v,LR as w,pg as x,Dk as y,BR as z,WR as A,us as B,Gt as C,Kg as D,_v as E,uC as F,ms as G,re as H,ws as I,bS as J,Bp as K,kS as L,Jp as M,vs as N,Jt as O,Ts as P,As as Q,em as R,ao as S,$e as T,we as U,cm as V,lm as W,dm as X,um as Y,Vs as Z,Xm as _,Ro as $,zm as aa,H0 as ba,I_ as ca,Mo as da,jN as ea};
1140
- //# sourceMappingURL=chunk-GWOJJ7FE.js.map
1140
+ //# sourceMappingURL=chunk-UQMJSMET.js.map
package/dist/cli.js CHANGED
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import{b as o}from"./chunk-JXF54PT7.js";import"./chunk-QIJLFPWE.js";var s=o(process.versions.node);s&&(console.error(s),process.exit(1));var{buildProgram:r}=await import("./program-IAOEFLZP.js"),{installCliSignalExit:i}=await import("./signal-exit-WL7G3EEZ.js");i();var e=await r();process.argv.slice(2).length===0?e.outputHelp():e.parse();
2
+ import{b as o}from"./chunk-JXF54PT7.js";import"./chunk-QIJLFPWE.js";var s=o(process.versions.node);s&&(console.error(s),process.exit(1));var{buildProgram:r}=await import("./program-RO5BWG6I.js"),{installCliSignalExit:i}=await import("./signal-exit-WL7G3EEZ.js");i();var e=await r();process.argv.slice(2).length===0?e.outputHelp():e.parse();
3
3
  //# sourceMappingURL=cli.js.map
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import{a as St,b as kt,c as vt,d as xt,da as Tt,e as $t,ea as Mt,f as Ct,g as Pt,h as bt}from"./chunk-GWOJJ7FE.js";import"./chunk-LKBUTSYP.js";import"./chunk-GTJIKXDB.js";import"./chunk-PS3UB5PH.js";import"./chunk-DG5I6PPM.js";import"./chunk-ZVP6GB4G.js";import"./chunk-S2GAEH2F.js";import"./chunk-VZLIBDLH.js";import"./chunk-EKJG63EJ.js";import"./chunk-IWEN3YNQ.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import"./chunk-ACFQBLPX.js";import"./chunk-LQE73AZR.js";import"./chunk-2D3RYIDU.js";import"./chunk-3Z5P2CWS.js";import"./chunk-E5OV6RTG.js";import"./chunk-PPUN7YHA.js";import{Z as yt,m as lt,n as ct,o as dt,p as mt,q as pt}from"./chunk-EWE2TJMN.js";import"./chunk-5PFTUGP4.js";import"./chunk-GLQLCBJS.js";import"./chunk-DP7RTNDM.js";import{a as L}from"./chunk-C245D4BZ.js";import{A as D,B as z,C as V,a as ye,b as we,c as Se,d as Ae,e as Ie,f as Oe,g as Ne,h as He,i as je,j as Ue,k as _e,l as I,m as q,n as Be,o as qe,p as Ye,q as O,r as ze,s as Ve,t as Xe,u as x,v as Y,w as Qe,x as Ze,y as et,z as wt}from"./chunk-74S7PKIX.js";import{a as B,b as M,c as F}from"./chunk-SFQUP3BP.js";import"./chunk-Y4CYQV7G.js";import"./chunk-LLNPKE7H.js";import"./chunk-SHEUCITK.js";import"./chunk-5EOFTPQB.js";import"./chunk-SZDACK6O.js";import"./chunk-76Z4VHDX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{s as ut}from"./chunk-M56MKNAG.js";import"./chunk-HJUBCA7O.js";import"./chunk-VWTBHLMX.js";import"./chunk-DS7CDASP.js";import{a as ht}from"./chunk-T2IDDOSX.js";import"./chunk-KA2UIZXG.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-BP52VVCW.js";import"./chunk-MYVHVJWZ.js";import"./chunk-DWADWDMU.js";import"./chunk-23A5K5UW.js";import"./chunk-QD6IICK7.js";import"./chunk-CECHWYJ2.js";import"./chunk-73NSSC6K.js";import{f as gt,g as ft}from"./chunk-OQHC7TJL.js";import"./chunk-WPNRDEHW.js";import"./chunk-2GIDVZ4H.js";import{j as it,k as rt,l as at}from"./chunk-MIRBKQHA.js";import"./chunk-72SZI2UW.js";import"./chunk-FX3D7YON.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import{a as ke,b as ve,c as xe,d as $e,e as Ce,f as Pe,g as be,h as Te,i as Me,j as Re,l as Ee,m as Ge,o as T,p as W}from"./chunk-5MUJZODV.js";import{a as m,b as G}from"./chunk-7I7IEX4S.js";import{b as Fe,c as Le,d as A,e as De}from"./chunk-JHCI6XCJ.js";import{a as Ke,b as Je,e as We}from"./chunk-DSYKYZMT.js";import{ca as tt,ea as st,fa as ot,ha as nt}from"./chunk-VUSDWZ6L.js";import"./chunk-RJ7DASOU.js";import"./chunk-BRK6M6LA.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";W();G();import{execa as Rt}from"execa";import{existsSync as se,promises as X}from"fs";import S from"path";import ie from"node-fetch";async function Et(o,e){let t=o.split("/");if(t.length<2)throw new Error(`Invalid skill package ID: ${o}. Expected format: owner/repo`);let s=t[0],i=t[1],n=t[2];try{let a=n?`${s}/${i}/${n}`:`${s}/${i}`;await Rt("npx",["-y","skills","add",a],{cwd:e,stdio:"pipe"}),m.success(`Installed skill package: ${o}`);let r=S.resolve(e,".skills",`${s}_${i}`);if(se(r))return await ne(r,o);let d=S.resolve(e,".skills");return se(d)?await ne(d,o):[]}catch{return m.info(`Fetching skills directly from GitHub: ${s}/${i}`),await Gt(s,i,n,e)}}async function Gt(o,e,t,s){let i=[];try{let n=`https://api.github.com/repos/${o}/${e}/git/trees/main?recursive=1`,a=await ie(n);if(!a.ok)throw new Error(`GitHub API error: ${a.status}`);let d=(await a.json()).tree.filter(p=>p.type==="blob"&&p.path.endsWith("SKILL.md"));if(t){let p=d.find(f=>f.path.includes(`/${t}/`)||f.path===`${t}/SKILL.md`);if(p){let f=await oe(o,e,p.path,s);f&&i.push(f)}}else for(let p of d){let f=await oe(o,e,p.path,s);f&&i.push(f)}}catch(n){m.error(`Failed to fetch skills from GitHub: ${n.message}`)}return i}async function oe(o,e,t,s){try{let i=`https://raw.githubusercontent.com/${o}/${e}/main/${t}`,n=await ie(i);if(!n.ok)return null;let a=await n.text(),r=A(a);if(r){r.source="remote",r.packageId=`${o}/${e}`;let d=S.dirname(t),p=S.resolve(s,".skills",`${o}_${e}`,d);await X.mkdir(p,{recursive:!0}),await X.writeFile(S.resolve(p,"SKILL.md"),a),r.path=S.resolve(p,"SKILL.md")}return r}catch{return null}}async function ne(o,e){let t=[],{default:s}=await import("fast-glob"),i=await s.glob("**/SKILL.md",{cwd:o,deep:5});for(let n of i)try{let a=S.resolve(o,n),r=await X.readFile(a,"utf8"),d=A(r);d&&(d.source="remote",d.path=a,d.packageId=e,t.push(d))}catch{}return t}async function At(o,e,t,s,i){let n=["---",`name: ${o}`,`description: ${e}`];if(s?.length){n.push("tags:");for(let a of s)n.push(` - ${a}`)}if(i?.length){n.push("globs:");for(let a of i)n.push(` - ${a}`)}return n.push("---"),`${n.join(`
1
+ import{a as St,b as kt,c as vt,d as xt,da as Tt,e as $t,ea as Mt,f as Ct,g as Pt,h as bt}from"./chunk-UQMJSMET.js";import"./chunk-LKBUTSYP.js";import"./chunk-GTJIKXDB.js";import"./chunk-PS3UB5PH.js";import"./chunk-DG5I6PPM.js";import"./chunk-ZVP6GB4G.js";import"./chunk-S2GAEH2F.js";import"./chunk-VZLIBDLH.js";import"./chunk-EKJG63EJ.js";import"./chunk-IWEN3YNQ.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import"./chunk-ACFQBLPX.js";import"./chunk-LQE73AZR.js";import"./chunk-2D3RYIDU.js";import"./chunk-3Z5P2CWS.js";import"./chunk-E5OV6RTG.js";import"./chunk-PPUN7YHA.js";import{Z as yt,m as lt,n as ct,o as dt,p as mt,q as pt}from"./chunk-EWE2TJMN.js";import"./chunk-5PFTUGP4.js";import"./chunk-GLQLCBJS.js";import"./chunk-DP7RTNDM.js";import{a as L}from"./chunk-C245D4BZ.js";import{A as D,B as z,C as V,a as ye,b as we,c as Se,d as Ae,e as Ie,f as Oe,g as Ne,h as He,i as je,j as Ue,k as _e,l as I,m as q,n as Be,o as qe,p as Ye,q as O,r as ze,s as Ve,t as Xe,u as x,v as Y,w as Qe,x as Ze,y as et,z as wt}from"./chunk-74S7PKIX.js";import{a as B,b as M,c as F}from"./chunk-SFQUP3BP.js";import"./chunk-Y4CYQV7G.js";import"./chunk-LLNPKE7H.js";import"./chunk-SHEUCITK.js";import"./chunk-5EOFTPQB.js";import"./chunk-SZDACK6O.js";import"./chunk-76Z4VHDX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{s as ut}from"./chunk-M56MKNAG.js";import"./chunk-HJUBCA7O.js";import"./chunk-VWTBHLMX.js";import"./chunk-DS7CDASP.js";import{a as ht}from"./chunk-T2IDDOSX.js";import"./chunk-KA2UIZXG.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-BP52VVCW.js";import"./chunk-MYVHVJWZ.js";import"./chunk-DWADWDMU.js";import"./chunk-23A5K5UW.js";import"./chunk-QD6IICK7.js";import"./chunk-CECHWYJ2.js";import"./chunk-73NSSC6K.js";import{f as gt,g as ft}from"./chunk-OQHC7TJL.js";import"./chunk-WPNRDEHW.js";import"./chunk-2GIDVZ4H.js";import{j as it,k as rt,l as at}from"./chunk-MIRBKQHA.js";import"./chunk-72SZI2UW.js";import"./chunk-FX3D7YON.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import{a as ke,b as ve,c as xe,d as $e,e as Ce,f as Pe,g as be,h as Te,i as Me,j as Re,l as Ee,m as Ge,o as T,p as W}from"./chunk-5MUJZODV.js";import{a as m,b as G}from"./chunk-7I7IEX4S.js";import{b as Fe,c as Le,d as A,e as De}from"./chunk-JHCI6XCJ.js";import{a as Ke,b as Je,e as We}from"./chunk-DSYKYZMT.js";import{ca as tt,ea as st,fa as ot,ha as nt}from"./chunk-VUSDWZ6L.js";import"./chunk-RJ7DASOU.js";import"./chunk-BRK6M6LA.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";W();G();import{execa as Rt}from"execa";import{existsSync as se,promises as X}from"fs";import S from"path";import ie from"node-fetch";async function Et(o,e){let t=o.split("/");if(t.length<2)throw new Error(`Invalid skill package ID: ${o}. Expected format: owner/repo`);let s=t[0],i=t[1],n=t[2];try{let a=n?`${s}/${i}/${n}`:`${s}/${i}`;await Rt("npx",["-y","skills","add",a],{cwd:e,stdio:"pipe"}),m.success(`Installed skill package: ${o}`);let r=S.resolve(e,".skills",`${s}_${i}`);if(se(r))return await ne(r,o);let d=S.resolve(e,".skills");return se(d)?await ne(d,o):[]}catch{return m.info(`Fetching skills directly from GitHub: ${s}/${i}`),await Gt(s,i,n,e)}}async function Gt(o,e,t,s){let i=[];try{let n=`https://api.github.com/repos/${o}/${e}/git/trees/main?recursive=1`,a=await ie(n);if(!a.ok)throw new Error(`GitHub API error: ${a.status}`);let d=(await a.json()).tree.filter(p=>p.type==="blob"&&p.path.endsWith("SKILL.md"));if(t){let p=d.find(f=>f.path.includes(`/${t}/`)||f.path===`${t}/SKILL.md`);if(p){let f=await oe(o,e,p.path,s);f&&i.push(f)}}else for(let p of d){let f=await oe(o,e,p.path,s);f&&i.push(f)}}catch(n){m.error(`Failed to fetch skills from GitHub: ${n.message}`)}return i}async function oe(o,e,t,s){try{let i=`https://raw.githubusercontent.com/${o}/${e}/main/${t}`,n=await ie(i);if(!n.ok)return null;let a=await n.text(),r=A(a);if(r){r.source="remote",r.packageId=`${o}/${e}`;let d=S.dirname(t),p=S.resolve(s,".skills",`${o}_${e}`,d);await X.mkdir(p,{recursive:!0}),await X.writeFile(S.resolve(p,"SKILL.md"),a),r.path=S.resolve(p,"SKILL.md")}return r}catch{return null}}async function ne(o,e){let t=[],{default:s}=await import("fast-glob"),i=await s.glob("**/SKILL.md",{cwd:o,deep:5});for(let n of i)try{let a=S.resolve(o,n),r=await X.readFile(a,"utf8"),d=A(r);d&&(d.source="remote",d.path=a,d.packageId=e,t.push(d))}catch{}return t}async function At(o,e,t,s,i){let n=["---",`name: ${o}`,`description: ${e}`];if(s?.length){n.push("tags:");for(let a of s)n.push(` - ${a}`)}if(i?.length){n.push("globs:");for(let a of i)n.push(` - ${a}`)}return n.push("---"),`${n.join(`
2
2
  `)}
3
3
 
4
4
  ${t}`}async function It(o){let{loadLocalSkills:e}=await import("./loader-YFVSSYSL.js");return e(o)}async function Ot(o,e,t,s,i){let a=[{role:"system",content:`You are a skill author for the Agent Skills ecosystem (skills.sh).
@@ -1,4 +1,4 @@
1
- import{a as Ql,b as js,g as Zl}from"./chunk-KA6K25T4.js";import{A as Xl,a as to,b as Dl,f as Pt,g as Ll,h as ql,i as Ul,j as Fl,l as Wl,m as Bl,r as Jl,s as Hl,t as Qi,u as Gl,x as Zi,y as Kl}from"./chunk-Q4R4OS5S.js";import{a as zl,c as Vl,d as Yl}from"./chunk-UVMCAZL7.js";import"./chunk-N7HKIMMR.js";import{a as Pl,c as Ml}from"./chunk-C6PWAEVX.js";import{a as Mi,b as lc}from"./chunk-RKPAVWXF.js";import{$ as Rl,A as al,B as cl,C as ll,D as dl,E as gl,F as ml,G as $l,H as Nt,I as Ss,J as Gi,K as bl,L as kl,M as vl,N as xl,O as Sl,P as El,Q as Rt,R as _t,S as Al,T as Tl,U as Me,V as Es,W as jn,X as zi,Y as jl,Z as Il,_ as Ki,a as yc,aa as As,b as wc,ba as Dt,ca as Ts,da as Xi,ea as _l,h as ps,i as vc,j as En,k as us,l as Ec,m as Ac,n as Lc,o as qc,p as bs,q as qi,r as Hc,s as Qc,t as Zc,u as tl,v as nl,w as sl,x as il,y as rl,z as Fi}from"./chunk-GWOJJ7FE.js";import{$a as Nl,A as ks,C as Xc,Ia as Ol,Ja as Vi,Ka as Cl,La as Yi,R as An,U as Wi,V as vs,W as pl,Za as ko,ba as Uo,ca as ul,da as Bi,fa as Ji,ha as fl,ia as hl,ja as Tn,na as xs,qa as yl,ra as wl,sa as Hi,w as Ui,x as Yc,z as Kc}from"./chunk-LKBUTSYP.js";import"./chunk-GTJIKXDB.js";import{a as $c,d as bc,e as kc}from"./chunk-PS3UB5PH.js";import"./chunk-DG5I6PPM.js";import"./chunk-ZVP6GB4G.js";import{a as fs,b as hs,c as Tc,d as jc,e as Oc,g as Cc,h as Ic,j as Nc,k as Rc,l as _c,m as Dc,p as ys,s as Pc,t as Mc}from"./chunk-S2GAEH2F.js";import"./chunk-VZLIBDLH.js";import{a as el,b as ol}from"./chunk-EKJG63EJ.js";import{a as xc,p as Sc}from"./chunk-IWEN3YNQ.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{b as oo}from"./chunk-ACFQBLPX.js";import{c as Uc,e as ws,g as $s}from"./chunk-LQE73AZR.js";import{a as Fc,b as Wc,c as Bc,d as Jc}from"./chunk-2D3RYIDU.js";import"./chunk-3Z5P2CWS.js";import{a as Gc,e as zc,g as Vc}from"./chunk-E5OV6RTG.js";import"./chunk-PPUN7YHA.js";import{I as qo,O as sc,Z as rc,g as Wa,r as Ba,y as _i,z as za}from"./chunk-EWE2TJMN.js";import{b as At,g as jt,h as gs,i as ms,j as Ot,k as Va,l as st,m as xn,u as ic}from"./chunk-5PFTUGP4.js";import{e as ec,f as Pi,k as oc}from"./chunk-GLQLCBJS.js";import{b as Tt}from"./chunk-DP7RTNDM.js";import"./chunk-74S7PKIX.js";import"./chunk-SFQUP3BP.js";import"./chunk-Y4CYQV7G.js";import{b as Sn}from"./chunk-LLNPKE7H.js";import{a as ac,b as cc}from"./chunk-SHEUCITK.js";import{a as Li,e as dc,f as gc,h as mc,i as pc,k as uc,l as fc,m as hc}from"./chunk-5EOFTPQB.js";import{c as Ka}from"./chunk-SZDACK6O.js";import{f as Xa,g as Qa,h as Di}from"./chunk-76Z4VHDX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{a as Ha,k as Za}from"./chunk-M56MKNAG.js";import{a as tc,b as re,c as Ie,d as It,e as nc}from"./chunk-HJUBCA7O.js";import"./chunk-VWTBHLMX.js";import{a as Ni}from"./chunk-DS7CDASP.js";import"./chunk-T2IDDOSX.js";import"./chunk-KA2UIZXG.js";import{a as Ri,b as Ja}from"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import{j as Ga}from"./chunk-X5C5W3E4.js";import{a as Ct}from"./chunk-GV7S5BAX.js";import{e as Ya}from"./chunk-GSX4NK2N.js";import"./chunk-BP52VVCW.js";import"./chunk-MYVHVJWZ.js";import{h as Fa}from"./chunk-DWADWDMU.js";import"./chunk-23A5K5UW.js";import"./chunk-QD6IICK7.js";import"./chunk-CECHWYJ2.js";import"./chunk-73NSSC6K.js";import{g as Lo,i as ds}from"./chunk-OQHC7TJL.js";import"./chunk-WPNRDEHW.js";import{b as Et,d as Ua}from"./chunk-2GIDVZ4H.js";import{a as Oi,b as va,c as Dp,d as as,e as xa,f as _a,g as Up,h as Da,i as Fp,m as St,n as Ma,o as La,s as qa,v as bo,w as vn}from"./chunk-MIRBKQHA.js";import{a as jo,b as xt,e as Ia,f as kn}from"./chunk-72SZI2UW.js";import{a as Pa,b as Wp}from"./chunk-FX3D7YON.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import"./chunk-JXF54PT7.js";import"./chunk-5MUJZODV.js";import{a as To,b as _p}from"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import{K as Ci,M as Ii,T as Lp,ca as Oa,da as Ca,ea as T,fa as ls,h as Sa,ha as te,i as Ea,j as Aa,l as Ta,m as Pp,w as ja,x as Mp}from"./chunk-VUSDWZ6L.js";import{a as Mo,i as cs}from"./chunk-RJ7DASOU.js";import"./chunk-BRK6M6LA.js";import"./chunk-2QNT5JDS.js";import{g as Na,k as Ra,l as qp}from"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{Command as Bp}from"commander";var ed=new Bp().name("a2a").description("start an A2A (Agent-to-Agent) protocol server for external agent integration").option("--port <port>","server port","3171").option("--host <host>","server host","0.0.0.0").option("-p, --provider <provider>","AI provider","claude-code").option("-m, --model <model>","model to use").option("--api-key <key>","API key for the provider").option("-c, --cwd <cwd>","working directory",process.cwd()).option("--no-cors","disable CORS headers").action(async e=>{await new wc({port:parseInt(e.port,10),host:e.host,provider:e.provider,model:e.model,apiKey:e.apiKey,cwd:e.cwd,cors:e.cors!==!1}).start()});te();import{Command as Jp}from"commander";import{execFileSync as io}from"node:child_process";import{cpSync as od,existsSync as tr,mkdirSync as er,mkdtempSync as Hp,readdirSync as Gp,rmSync as td,writeFileSync as nd}from"node:fs";import{dirname as sd,join as qe}from"node:path";import{homedir as Os,release as zp,tmpdir as Vp}from"node:os";import{setTimeout as Yp}from"node:timers/promises";function Cs(){let e=Tc(process.platform,process.arch,zp());if(e)throw new Error(e)}function Is(){let e=qe(Os(),"Library/LaunchAgents"),o=[];try{o=Gp(e).filter(Cc)}catch{}let t=o.flatMap(n=>{let s=qe(e,n);try{return[{file:s,plist:io("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return Ic(e,t)}function On(e){return`gui/${process.getuid()}/${e.label}`}async function or(e){try{io("launchctl",["bootout",On(e)],{stdio:"pipe"})}catch{}for(let o=0;o<30;o++){try{io("launchctl",["print",On(e)],{stdio:"pipe"})}catch{return}await Yp(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function id(e){if(!tr(e.file))throw new Error("Run agentx desktop install first.");let o=!0;try{io("launchctl",["print",On(e)],{stdio:"pipe"})}catch{o=!1}o||io("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),io("launchctl",["kickstart",On(e)],{stdio:"pipe"})}function Kp(){let e=Dc();if(e&&tr(qe(e,"apps/mac-voice/build.sh")))return e;throw new Error("Desktop sources are missing from this installation. Update AgentX to a release containing apps/mac-voice and apps/mac-helper.")}var Mt=new Jp("desktop").description("install and control the macOS desktop assistant");Mt.command("install").description("build, install, and start voice and computer-use helpers at login").option("--agent <id>","pin this agent; without it, pick the agent from the menu-bar icon").option("--dry-run","show the installation plan without building or changing login items").action(async e=>{Cs();let o=T(),t=jc(o.agents,e.agent),n=e.agent,s=o.dashboard?.daemonUrl||`http://${o.node.bind.replace(/^0\.0\.0\.0:/,"127.0.0.1:")}`,i=Kp(),r=qe(Os(),"Applications"),{keep:a,remove:c}=Is();if(console.log(`Desktop assistant \u2192 ${qe(r,fs)}
1
+ import{a as Ql,b as js,g as Zl}from"./chunk-KA6K25T4.js";import{A as Xl,a as to,b as Dl,f as Pt,g as Ll,h as ql,i as Ul,j as Fl,l as Wl,m as Bl,r as Jl,s as Hl,t as Qi,u as Gl,x as Zi,y as Kl}from"./chunk-Q4R4OS5S.js";import{a as zl,c as Vl,d as Yl}from"./chunk-UVMCAZL7.js";import"./chunk-N7HKIMMR.js";import{a as Pl,c as Ml}from"./chunk-C6PWAEVX.js";import{a as Mi,b as lc}from"./chunk-RKPAVWXF.js";import{$ as Rl,A as al,B as cl,C as ll,D as dl,E as gl,F as ml,G as $l,H as Nt,I as Ss,J as Gi,K as bl,L as kl,M as vl,N as xl,O as Sl,P as El,Q as Rt,R as _t,S as Al,T as Tl,U as Me,V as Es,W as jn,X as zi,Y as jl,Z as Il,_ as Ki,a as yc,aa as As,b as wc,ba as Dt,ca as Ts,da as Xi,ea as _l,h as ps,i as vc,j as En,k as us,l as Ec,m as Ac,n as Lc,o as qc,p as bs,q as qi,r as Hc,s as Qc,t as Zc,u as tl,v as nl,w as sl,x as il,y as rl,z as Fi}from"./chunk-UQMJSMET.js";import{$a as Nl,A as ks,C as Xc,Ia as Ol,Ja as Vi,Ka as Cl,La as Yi,R as An,U as Wi,V as vs,W as pl,Za as ko,ba as Uo,ca as ul,da as Bi,fa as Ji,ha as fl,ia as hl,ja as Tn,na as xs,qa as yl,ra as wl,sa as Hi,w as Ui,x as Yc,z as Kc}from"./chunk-LKBUTSYP.js";import"./chunk-GTJIKXDB.js";import{a as $c,d as bc,e as kc}from"./chunk-PS3UB5PH.js";import"./chunk-DG5I6PPM.js";import"./chunk-ZVP6GB4G.js";import{a as fs,b as hs,c as Tc,d as jc,e as Oc,g as Cc,h as Ic,j as Nc,k as Rc,l as _c,m as Dc,p as ys,s as Pc,t as Mc}from"./chunk-S2GAEH2F.js";import"./chunk-VZLIBDLH.js";import{a as el,b as ol}from"./chunk-EKJG63EJ.js";import{a as xc,p as Sc}from"./chunk-IWEN3YNQ.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{b as oo}from"./chunk-ACFQBLPX.js";import{c as Uc,e as ws,g as $s}from"./chunk-LQE73AZR.js";import{a as Fc,b as Wc,c as Bc,d as Jc}from"./chunk-2D3RYIDU.js";import"./chunk-3Z5P2CWS.js";import{a as Gc,e as zc,g as Vc}from"./chunk-E5OV6RTG.js";import"./chunk-PPUN7YHA.js";import{I as qo,O as sc,Z as rc,g as Wa,r as Ba,y as _i,z as za}from"./chunk-EWE2TJMN.js";import{b as At,g as jt,h as gs,i as ms,j as Ot,k as Va,l as st,m as xn,u as ic}from"./chunk-5PFTUGP4.js";import{e as ec,f as Pi,k as oc}from"./chunk-GLQLCBJS.js";import{b as Tt}from"./chunk-DP7RTNDM.js";import"./chunk-74S7PKIX.js";import"./chunk-SFQUP3BP.js";import"./chunk-Y4CYQV7G.js";import{b as Sn}from"./chunk-LLNPKE7H.js";import{a as ac,b as cc}from"./chunk-SHEUCITK.js";import{a as Li,e as dc,f as gc,h as mc,i as pc,k as uc,l as fc,m as hc}from"./chunk-5EOFTPQB.js";import{c as Ka}from"./chunk-SZDACK6O.js";import{f as Xa,g as Qa,h as Di}from"./chunk-76Z4VHDX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{a as Ha,k as Za}from"./chunk-M56MKNAG.js";import{a as tc,b as re,c as Ie,d as It,e as nc}from"./chunk-HJUBCA7O.js";import"./chunk-VWTBHLMX.js";import{a as Ni}from"./chunk-DS7CDASP.js";import"./chunk-T2IDDOSX.js";import"./chunk-KA2UIZXG.js";import{a as Ri,b as Ja}from"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import{j as Ga}from"./chunk-X5C5W3E4.js";import{a as Ct}from"./chunk-GV7S5BAX.js";import{e as Ya}from"./chunk-GSX4NK2N.js";import"./chunk-BP52VVCW.js";import"./chunk-MYVHVJWZ.js";import{h as Fa}from"./chunk-DWADWDMU.js";import"./chunk-23A5K5UW.js";import"./chunk-QD6IICK7.js";import"./chunk-CECHWYJ2.js";import"./chunk-73NSSC6K.js";import{g as Lo,i as ds}from"./chunk-OQHC7TJL.js";import"./chunk-WPNRDEHW.js";import{b as Et,d as Ua}from"./chunk-2GIDVZ4H.js";import{a as Oi,b as va,c as Dp,d as as,e as xa,f as _a,g as Up,h as Da,i as Fp,m as St,n as Ma,o as La,s as qa,v as bo,w as vn}from"./chunk-MIRBKQHA.js";import{a as jo,b as xt,e as Ia,f as kn}from"./chunk-72SZI2UW.js";import{a as Pa,b as Wp}from"./chunk-FX3D7YON.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import"./chunk-JXF54PT7.js";import"./chunk-5MUJZODV.js";import{a as To,b as _p}from"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import{K as Ci,M as Ii,T as Lp,ca as Oa,da as Ca,ea as T,fa as ls,h as Sa,ha as te,i as Ea,j as Aa,l as Ta,m as Pp,w as ja,x as Mp}from"./chunk-VUSDWZ6L.js";import{a as Mo,i as cs}from"./chunk-RJ7DASOU.js";import"./chunk-BRK6M6LA.js";import"./chunk-2QNT5JDS.js";import{g as Na,k as Ra,l as qp}from"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{Command as Bp}from"commander";var ed=new Bp().name("a2a").description("start an A2A (Agent-to-Agent) protocol server for external agent integration").option("--port <port>","server port","3171").option("--host <host>","server host","0.0.0.0").option("-p, --provider <provider>","AI provider","claude-code").option("-m, --model <model>","model to use").option("--api-key <key>","API key for the provider").option("-c, --cwd <cwd>","working directory",process.cwd()).option("--no-cors","disable CORS headers").action(async e=>{await new wc({port:parseInt(e.port,10),host:e.host,provider:e.provider,model:e.model,apiKey:e.apiKey,cwd:e.cwd,cors:e.cors!==!1}).start()});te();import{Command as Jp}from"commander";import{execFileSync as io}from"node:child_process";import{cpSync as od,existsSync as tr,mkdirSync as er,mkdtempSync as Hp,readdirSync as Gp,rmSync as td,writeFileSync as nd}from"node:fs";import{dirname as sd,join as qe}from"node:path";import{homedir as Os,release as zp,tmpdir as Vp}from"node:os";import{setTimeout as Yp}from"node:timers/promises";function Cs(){let e=Tc(process.platform,process.arch,zp());if(e)throw new Error(e)}function Is(){let e=qe(Os(),"Library/LaunchAgents"),o=[];try{o=Gp(e).filter(Cc)}catch{}let t=o.flatMap(n=>{let s=qe(e,n);try{return[{file:s,plist:io("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return Ic(e,t)}function On(e){return`gui/${process.getuid()}/${e.label}`}async function or(e){try{io("launchctl",["bootout",On(e)],{stdio:"pipe"})}catch{}for(let o=0;o<30;o++){try{io("launchctl",["print",On(e)],{stdio:"pipe"})}catch{return}await Yp(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function id(e){if(!tr(e.file))throw new Error("Run agentx desktop install first.");let o=!0;try{io("launchctl",["print",On(e)],{stdio:"pipe"})}catch{o=!1}o||io("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),io("launchctl",["kickstart",On(e)],{stdio:"pipe"})}function Kp(){let e=Dc();if(e&&tr(qe(e,"apps/mac-voice/build.sh")))return e;throw new Error("Desktop sources are missing from this installation. Update AgentX to a release containing apps/mac-voice and apps/mac-helper.")}var Mt=new Jp("desktop").description("install and control the macOS desktop assistant");Mt.command("install").description("build, install, and start voice and computer-use helpers at login").option("--agent <id>","pin this agent; without it, pick the agent from the menu-bar icon").option("--dry-run","show the installation plan without building or changing login items").action(async e=>{Cs();let o=T(),t=jc(o.agents,e.agent),n=e.agent,s=o.dashboard?.daemonUrl||`http://${o.node.bind.replace(/^0\.0\.0\.0:/,"127.0.0.1:")}`,i=Kp(),r=qe(Os(),"Applications"),{keep:a,remove:c}=Is();if(console.log(`Desktop assistant \u2192 ${qe(r,fs)}
2
2
  Computer-use helper \u2192 ${qe(r,hs)}
3
3
  Agent \u2192 ${n?`${t} (pinned)`:"picked from the menu-bar icon"}
4
4
  Daemon \u2192 ${s}
@@ -448,7 +448,7 @@ return aid ?? null`}function Jh(e,o){if(e.kind==="path"){let s=e.pts,i=s[Math.fl
448
448
  Latest runs (${s.length})`),s.length===0&&console.log(G.dim(" nothing recorded yet"));for(let r of s){let a=r.status==="ok"?G.green("ok"):r.status==="in-flight"?G.yellow("running"):G.red(r.status);console.log(` ${G.dim(am(r.startedAt))} ${(r.channel??"?").padEnd(9)} ${r.agentId} ${a} ${cm(r.messagePreview)}`)}console.log()});cs();Mp();import{Command as Qy}from"commander";import{existsSync as Zy}from"fs";import ye from"chalk";var Zt=new Qy("requests").description("what you asked agents for that is not finished, oldest first"),pm={in_progress:"in progress",waiting_owner:"waiting on you",waiting_other:"waiting on another agent",needs_attention:"needs attention",done:"done",declined:"declined",dropped:"dropped"};function Wr(){if(!Zy(tc()))return console.error(ye.red(" no agentx.json here: run this from the install folder, the one that holds agentx.json")),process.exitCode=1,null;let e=Mo();return e?new ja(e):(process.exitCode=1,null)}var ii=e=>new Date(e).toISOString().slice(0,16).replace("T"," ")+" UTC";function um(e){let o=e.state==="needs_attention"?ye.red:e.state==="waiting_owner"?ye.yellow:ye.dim;console.log(` ${ye.cyan(e.id)} ${o(`[${pm[e.state]??e.state}]`)} ${ye.dim(`${ii(e.createdAt)} \xB7 ${e.channel} \xB7 ${e.agentId}`)}`),console.log(` ${e.text.replace(/\s+/g," ").trim().slice(0,240)}`),e.state==="waiting_owner"&&e.question&&console.log(ye.yellow(` Question: ${e.question}`)),e.state==="needs_attention"&&e.attentionReason&&console.log(ye.red(` ${e.attentionReason}`)),e.evidence&&console.log(ye.green(` Evidence: ${e.evidence}`)),e.closeReason&&console.log(ye.dim(` Reason: ${e.closeReason}`))}Zt.command("list",{isDefault:!0}).alias("ls").description("open requests, oldest first").option("--json","machine-readable output").action(e=>{let o=Wr();if(!o)return;let t=o.listOpen();if(e.json){console.log(JSON.stringify(t,null,2));return}if(Ui().enabled||console.log(ye.dim(" requests are off: turn them on with `agentx requests settings --enabled on`")),t.length===0){console.log(ye.dim(" no open requests"));return}for(let n of t)um(n);console.log(ye.dim(`
449
449
  ${t.length} open. Close one: agentx requests done <id> --evidence <link> \xB7 agentx requests drop <id>`))});Zt.command("show <id>").description("one request and the runs, delegations and cards linked to it").action(e=>{let o=Wr();if(!o)return;let t=o.get(e);if(!t||t.state==="candidate"){console.error(ye.red(` no request "${e}"`)),process.exitCode=1;return}um(t),console.log(ye.dim(` Last activity ${ii(t.updatedAt)}${t.closedAt?` \xB7 closed ${ii(t.closedAt)}`:""}`));for(let n of o.links(e))console.log(ye.dim(` ${n.kind} ${n.ref} (${ii(n.at)})`))});function fm(e,o,t,n){Zt.command(`${e} <id>`).description(o).option(t,e==="done"?"link to the proof: PR, issue, message, deploy":"why it is dropped").action((s,i)=>{let r=Wr();if(!r)return;let a=e==="done"?i.evidence:i.reason??"dropped by the owner";if(!a){console.error(ye.red(` ${n}`)),process.exitCode=1;return}let c=r.get(s);if(!c||c.state==="candidate"){console.error(ye.red(` no request "${s}"`)),process.exitCode=1;return}if(!r.close(s,e==="done"?"done":"dropped",a,Date.now())){console.error(ye.red(` ${s} is already closed (${pm[c.state]??c.state})`)),process.exitCode=1;return}console.log(ye.green(` \u2713 ${s} ${e==="done"?"closed as done":"dropped"}`))})}fm("done","close a request as finished, with a link to the evidence","--evidence <link>","a finished request needs --evidence <link>");fm("drop","drop a request you no longer want","--reason <text>","");Zt.command("settings").description("show or change the requests settings").option("--enabled <on|off>","record and follow your requests").option("--from <id,...>",'who counts as you on channels other people can reach, as channel:id (your login on GitLab and GitHub, your sender id elsewhere); "none" to clear').option("--channels <name,...>",'channels to record on; "all" for every channel a person writes on').option("--stale-hours <n>","hours without activity before an open request comes back to you").option("--retention-days <n>","days a closed request is kept").action(async e=>{let o={};try{let n=(i,r)=>{if(r===void 0)return;let a=Number(r);if(!(a>0))throw new Error(`${i} must be a positive number`);return a},s=(i,r)=>i===void 0?void 0:i===r?[]:i.split(",").map(a=>a.trim()).filter(Boolean);if(e.enabled!==void 0){if(e.enabled!=="on"&&e.enabled!=="off")throw new Error("--enabled takes on or off");o.enabled=e.enabled==="on"}o.from=s(e.from,"none"),o.channels=s(e.channels,"all"),o.staleAfterHours=n("--stale-hours",e.staleHours),o.retentionDays=n("--retention-days",e.retentionDays)}catch(n){console.error(ye.red(` ${n.message}`)),process.exitCode=1;return}if(Object.values(o).some(n=>n!==void 0)){let n=await Yc(o);if(!n.success){console.error(ye.red(` ${n.error}`)),process.exitCode=1;return}console.log(ye.green(" \u2713 saved")+(n.reloaded?ye.dim(" (daemon reloaded)"):""))}let t=Ui();console.log(` Requests ${t.enabled?"on":"off"}`),console.log(` Channels ${t.channels.length?t.channels.join(", "):"every channel a person writes on"}`),console.log(` Counts as you ${t.from.length?t.from.join(", "):"only voice, the app and the dashboard on this machine"}`),console.log(` Comes back after ${t.staleAfterHours} hour(s) without activity`),console.log(` Closed requests kept ${t.retentionDays} day(s)`)});import{Command as ew}from"commander";import en from"chalk";te();var hm=new ew("request-status").description("show each person the state of their request in the thread where they asked (GitLab, GitHub)").argument("[channel]",Qi.join(" or ")).argument("[state]","on or off").action(async(e,o)=>{if(e!==void 0){o!=="on"&&o!=="off"&&(console.error(en.red("\u2717 say on or off, for example: agentx request-status gitlab on")),process.exit(1));let n="",s=await re(i=>{n=Gl(i,e,o==="on")});s.success||(console.error(en.red(`\u2717 ${s.error}`)),process.exit(1)),console.log(en.green(`\u2713 ${n}`)),s.reloaded&&console.log(en.dim(" daemon hot-reloaded"))}let t=T().requestStatus.channels.map(n=>n.toLowerCase());for(let n of Qi)console.log(` ${n.padEnd(8)} ${t.includes(n)?en.green("on"):en.dim("off")}`)});import{Command as xw}from"commander";import on from"chalk";import ce from"chalk";import Vn from"prompts";import{readFileSync as ow,writeFileSync as tw,existsSync as nw}from"fs";import{resolve as ym}from"path";var sw=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function iw(e){let o=e.trim();return o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'")?o.slice(1,-1):o}function Br(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function wm(e=".env"){let o=ym(e);if(!nw(o))return[];let t=ow(o,"utf-8"),n=[];for(let s of t.split(/\r?\n/)){if(s.trim()===""){n.push({kind:"blank",raw:s});continue}if(s.trim().startsWith("#")){n.push({kind:"comment",raw:s});continue}let i=s.match(sw);i?n.push({kind:"kv",key:i[1],value:iw(i[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function rw(e){return e.map(o=>o.kind==="kv"?`${o.key}=${Br(o.value)}`:o.raw).join(`
450
450
  `)+`
451
- `}function zn(e,o,t=".env"){let n=ym(t),s=wm(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:o,raw:`${e}=${Br(o)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:o,raw:`${e}=${Br(o)}`})),tw(n,rw(s))}function Jr(e,o=".env"){return wm(o).find(s=>s.kind==="kv"&&s.key===e)?.value}var $m="https://t.me/BotFather";async function aw(e){try{let o=await fetch(`https://api.telegram.org/bot${e}/getMe`,{signal:AbortSignal.timeout(8e3)});if(!o.ok)return null;let t=await o.json();return t?.ok?t.result:null}catch{return null}}async function cw(e,o){let t=Date.now()+o,n=0;try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=-1&timeout=0`,{signal:AbortSignal.timeout(5e3)})).json();i?.result?.length&&(n=i.result[0].update_id+1)}catch{}for(;Date.now()<t;)try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=${n}&timeout=10`,{signal:AbortSignal.timeout(15e3)})).json();for(let r of i?.result||[]){n=Math.max(n,r.update_id+1);let a=r.message||r.edited_message||r.channel_post;if(a?.chat?.id)return{chatId:a.chat.id,chatTitle:a.chat.title||a.chat.username||a.chat.first_name,from:a.from?.first_name||a.from?.username||"unknown"}}}catch{}return null}async function bm(e={}){console.log(),console.log(ce.bold(" Connect Telegram")),console.log(),console.log(ce.dim(` 1. Open ${$m}`)),console.log(ce.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(ce.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{wantsBrowser:o}=await Vn({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});o&&at($m);let{token:t}=await Vn({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:b=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(b.trim())||"That doesn't look like a Telegram token"});t||(console.log(ce.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await aw(t.trim());n||(console.log(ce.red("\u2717 invalid or revoked")),process.exit(1)),console.log(ce.green(`\u2713 ${n.first_name} (@${n.username})`));let{readFileSync:s,existsSync:i}=await import("fs"),{resolve:r}=await import("path"),a=e.configPath||r(process.cwd(),"agentx.json");i(a)||(console.log(ce.red(` No agentx.json at ${a}. Run: agentx init`)),process.exit(1));let c=JSON.parse(s(a,"utf-8")),l=Object.keys(c.agents||{});l.length===0&&(console.log(ce.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await Vn({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map($=>({title:$,value:$})),initial:0})).agent),g||(console.log(ce.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},u=e.account||g;d[u]&&d[u].agentBinding!==g&&(u=(await Vn({type:"text",name:"account",message:`Account "${u}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:$=>/^[a-z0-9-]+$/i.test($)||"lowercase letters, digits, hyphens only"})).account),u||(console.log(ce.red(" Aborted")),process.exit(1));let f=`TG_${u.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;zn(f,t.trim()),process.env[f]=t.trim();let p=await re(b=>{Ie(b,"channels.telegram.enabled",!0),Ie(b,`channels.telegram.accounts.${u}`,{token:`\${${f}}`,agentBinding:g});let $=It(b,`agents.${g}.mentions`)||[],E=`@${n.username}`;$.includes(E)||($.push(E),Ie(b,`agents.${g}.mentions`,$))},{configPath:e.configPath});if(p.success||(console.log(ce.red(` \u2717 ${p.error}`)),process.exit(1)),console.log(),console.log(ce.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(ce.dim(` Token stored in .env as ${f}`)),console.log(ce.dim(` Mentions updated to include @${n.username}`)),p.reloaded?console.log(ce.dim(" Daemon hot-reloaded.")):console.log(ce.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:y}=await Vn({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!y)return;console.log(),console.log(ce.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(ce.dim(" Waiting up to 90s..."));let w=await cw(t.trim(),9e4);if(!w){console.log(ce.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(ce.dim(" agentx config set notifications.destination.channel telegram")),console.log(ce.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(ce.dim(` agentx config set notifications.destination.accountId ${u}`));return}let k=await re(b=>{Ie(b,"notifications.destination",{channel:"telegram",chatId:String(w.chatId),accountId:u})},{configPath:e.configPath});if(!k.success){console.log(ce.red(` \u2717 failed to save destination: ${k.error}`));return}console.log(ce.green(" \u2713 Default --notify target set")),console.log(ce.dim(` Chat: ${w.chatTitle||w.chatId} (from ${w.from})`)),console.log(ce.dim(" From now on, --notify me resolves to this chat.")),k.reloaded&&console.log(ce.dim(" Daemon hot-reloaded."))}import ve from"chalk";import Hr from"prompts";import{existsSync as zr,mkdirSync as lw,readdirSync as dw,readFileSync as km}from"fs";import{resolve as Gr}from"path";var gw=".agentx/whatsapp-sessions";function mw(){let e=Gr(process.cwd(),".agentx/daemon.pid");if(!zr(e))return!1;try{let o=parseInt(km(e,"utf-8").trim(),10);return o?(process.kill(o,0),!0):!1}catch{return!1}}function pw(e){if(!zr(e))return!1;try{return dw(e).some(o=>o.includes("creds")||o.endsWith(".json"))}catch{return!1}}async function uw(e,o){let t;try{t=await import("@whiskeysockets/baileys")}catch{return o(ve.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),o(ve.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=t.default||t;lw(e,{recursive:!0});let{state:i,saveCreds:r}=await s(e),a;try{a=(await t.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:i.creds,keys:t.makeCacheableSignalKeyStore?t.makeCacheableSignalKeyStore(i.keys,c):i.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",r),await new Promise(g=>{let u=setTimeout(()=>{o(ve.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}g(!1)},12e4);l.ev.on("connection.update",async f=>{if(f.qr){o(ve.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),o("");try{let{default:p}=await import("qrcode-terminal");p.generate(f.qr,{small:!0})}catch{o(` QR: ${f.qr}`)}o("")}if(f.connection==="open"){clearTimeout(u),o(ve.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(u),o(ve.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function vm(e={}){if(console.log(),console.log(ve.bold(" Connect WhatsApp")),console.log(),mw()){console.log(ve.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(ve.dim(" agentx daemon stop")),console.log();let{cont:l}=await Hr({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(ve.red(" Aborted")),process.exit(1))}let o=e.configPath||Gr(process.cwd(),"agentx.json");zr(o)||(console.log(ve.red(` No agentx.json at ${o}. Run: agentx init`)),process.exit(1));let t=JSON.parse(km(o,"utf-8")),n=e.sessionDir||t.channels?.whatsapp?.sessionDir||gw,s=Gr(process.cwd(),n),i=Object.keys(t.agents||{});i.length===0&&(console.log(ve.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await Hr({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(g=>({title:g,value:g})),initial:0})).agent),r||(console.log(ve.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(pw(s)&&a){let{keep:l}=await Hr({type:"confirm",name:"keep",message:`An existing session was found at ${n}. Keep it (recommended), or pair again?`,initial:!0});a=!l,l&&console.log(ve.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await uw(s,g=>console.log(g))||(console.log(ve.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await re(l=>{Ie(l,"channels.whatsapp.enabled",!0),Ie(l,"channels.whatsapp.sessionDir",n),Ie(l,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(ve.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(ve.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(ve.dim(` Session: ${n}`)),console.log(ve.dim(" Start the daemon to begin receiving:")),console.log(ve.dim(" agentx daemon start")),console.log(ve.dim(" Add routes later with:")),console.log(ve.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as fw}from"crypto";import je from"chalk";import xm from"prompts";var ri="agentx-mesh:",ai="//join/";function hw(e){return Buffer.from(e,"utf-8").toString("base64url")}function yw(e){return Buffer.from(e,"base64url").toString("utf-8")}function ww(e){return`${ri}${ai}${hw(JSON.stringify(e))}`}function $w(e){if(!e.startsWith(`${ri}${ai}`))throw new Error(`Not a mesh invite link \u2014 expected ${ri}${ai}\u2026`);let o=e.slice(ri.length+ai.length),t=JSON.parse(yw(o));if(t.version!==1)throw new Error(`Unsupported invite version: ${t.version}`);if(typeof t.url!="string"||typeof t.token!="string"||typeof t.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return t}function bw(){return fw(32).toString("hex")}function kw(e){let o=e?.node?.bind||"127.0.0.1:18800",[t,n]=o.split(":");return`http://${t}:${n}`}function vw(e){return e?.node?.name||e?.node?.id||"node"}async function Sm(e){let{readFileSync:o,existsSync:t}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");t(s)||(console.log(je.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(o(s,"utf-8")),r=Jr("MESH_TOKEN");r||(r=bw(),zn("MESH_TOKEN",r),console.log(je.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||kw(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await xm({type:"text",name:"url",message:"This node's URL as peers should reach it (e.g. http://100.x.x.x:18800):",initial:a,validate:u=>/^https?:\/\//.test(u)||"must start with http:// or https://"});d||(console.log(je.red(" Aborted")),process.exit(1)),a=d}let l=await re(d=>{Ie(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(je.red(` \u2717 ${l.error}`)),process.exit(1));let g=ww({url:a,token:r,name:vw(i),version:1});console.log(),console.log(je.bold(" Mesh invite")),console.log(),console.log(` ${je.cyan(g)}`),console.log(),console.log(je.dim(" Run on the other node:")),console.log(je.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(je.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function Em(e,o={}){let t;try{t=$w(e)}catch(i){console.log(je.red(` \u2717 ${i.message}`)),process.exit(1)}let n=Jr("MESH_TOKEN");if(n&&n!==t.token){let{overwrite:i}=await xm({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(je.red(" Aborted (keeping existing .env)")),process.exit(1))}zn("MESH_TOKEN",t.token);let s=await re(i=>{Ie(i,"mesh.enabled",!0);let r=It(i,"mesh.peers")||[],a=r.findIndex(l=>l.name===t.name),c={name:t.name,url:t.url,token:"${MESH_TOKEN}"};a>=0?r[a]=c:r.push(c),Ie(i,"mesh.peers",r)},{configPath:o.configPath});s.success||(console.log(je.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(je.green(" \u2713 Joined mesh")),console.log(je.dim(` Peer: ${t.name} @ ${t.url}`)),console.log(je.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(je.dim(" Daemon hot-reloaded.")):console.log(je.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let i=await fetch(`${t.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(i.ok){let r=await i.json(),a=Array.isArray(r.agents)?r.agents.length:"?";console.log(je.dim(` Reachable \u2014 ${t.name} exposes ${a} agents`))}else console.log(je.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(je.yellow(` Could not reach ${t.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var tn=new xw().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");tn.command("telegram").description("pair a Telegram bot \u2014 persists token in .env, binds to an agent, auto-detects default chat").option("--agent <id>","agent to bind the bot to (skips the prompt)").option("--account <name>","account label in channels.telegram.accounts (defaults to agent id)").option("--skip-chat-capture","don't listen for the first message after pairing").option("-c, --config <path>","path to agentx.json").action(async e=>{await bm({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});tn.command("whatsapp").description("pair WhatsApp via QR (prints in terminal), then writes channels.whatsapp config").option("--agent <id>","default agent for inbound messages").option("--session-dir <path>","session directory (default: .agentx/whatsapp-sessions)").option("--skip-pair","skip QR pairing (use when session already exists)").option("-c, --config <path>","path to agentx.json").action(async e=>{await vm({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var Am=tn.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");Am.command("invite").description("emit a single-use join link for another AgentX node").option("--url <url>","this node's URL as peers should reach it (Tailscale IP etc.)").option("-c, --config <path>","path to agentx.json").action(async e=>{await Sm({url:e.url,configPath:e.config})});Am.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(e,o)=>{await Em(e,{configPath:o.config})});tn.action(()=>{console.log(),console.log(on.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${on.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${on.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${on.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${on.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(on.dim(" GitLab connect is the next slice.")),console.log()});te();import{Command as Sw}from"commander";import oe from"chalk";var nn=new Sw().name("usage").description("token usage analysis and reporting");nn.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=T(),[o,t]=e.node.bind.split(":"),s=await(await fetch(`http://${o||"127.0.0.1"}:${t}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(oe.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(oe.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${oe.bold(i(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${i(s.totalInput)}`),console.log(` Output: ${i(s.totalOutput)}`),console.log(` Cache read: ${i(s.totalCacheRead)}`),console.log(` Cache create: ${i(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${oe.red(String(s.totalErrors))}`),console.log(),console.log(oe.bold(" By Agent:"));let r=Object.entries(s.byAgent||{});r.sort((a,c)=>c[1].total-a[1].total);for(let[a,c]of r){let l=i(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${oe.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${oe.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(oe.red(" Daemon not running. Start with: agentx daemon start")):console.log(oe.red(` ${e.message}`))}});nn.command("plan").description("show the Claude plan windows as Claude Code last reported them, and any hold on fresh sessions").option("--lift","lift the hold on fresh sessions now, without waiting for the reset time").option("--json","raw JSON output").action(async e=>{try{let o=T(),[t,n]=o.node.bind.split(":"),s=`http://${t||"127.0.0.1"}:${n}`,i=e.lift?await fetch(`${s}/usage/plan/lift`,{method:"POST",signal:AbortSignal.timeout(3e3)}):await fetch(`${s}/usage/plan`,{signal:AbortSignal.timeout(3e3)});if(!i.ok)throw new Error(`Daemon answered ${i.status}. It may be older than this command; restart it.`);let r=await i.json();if(e.json){console.log(JSON.stringify(r,null,2));return}let a=d=>d.replace(/_/g," ");if(console.log(),e.lift){let d=r.lifted.map(u=>a(u.window));console.log(d.length?` Lifted the hold on: ${d.join(", ")}. The next fresh session asks Claude again.`:oe.dim(" No hold to lift.")),console.log();return}let c=r.now,l=new Set(r.holds.map(d=>d.window));console.log(oe.bold(" Claude plan (as Claude Code last reported it)")),console.log(),r.provider.length===0&&console.log(oe.dim(" No report yet. Claude Code reports on each turn; the list is empty after a daemon restart."));for(let d of r.provider){let u=d.usingOverage?"extra usage":d.status==="allowed_warning"?"nearly full":d.status,f=typeof d.utilization=="number"?`${Math.round(d.utilization*100)}% used`:"",p=Math.max(1,Math.round((d.resetsAt-c)/6e4)),y=d.resetsAt>c?p<60?`resets in ${p} min`:p<48*60?`resets in ${Math.round(p/60)} h`:`resets in ${Math.round(p/1440)} days`:"",w=l.has(d.window)?oe.red("holding fresh sessions"):"";console.log(` ${a(d.window).padEnd(18)} ${u.padEnd(12)} ${[f,y,w].filter(Boolean).join(", ")}`)}console.log();let g=d=>d?` of ${d}`:"";console.log(` Fresh sessions started: ${r.lastHour}${g(r.maxPerHour)} in the last hour, ${r.last5h}${g(r.maxPer5h)} in the last 5 hours`),l.size&&console.log(oe.dim(" To try again now: agentx usage plan --lift")),console.log()}catch(o){o.cause?.code==="ECONNREFUSED"?console.log(oe.red(" Daemon not running. Start with: agentx daemon start")):console.log(oe.red(` ${o.message}`))}});nn.command("report").description("run full session analysis (parses Claude Code JSONL files)").option("--days <n>","analyze last N days","7").action(async e=>{let{execSync:o}=await import("child_process"),{existsSync:t}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!t(s)){console.log(oe.red(` Script not found: ${s}`)),console.log(oe.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(oe.dim(" Analyzing Claude Code sessions..."));try{o(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(oe.red(" Analysis failed. Is Python 3 installed?"))}});nn.command("surfaces").description("which CLI commands and dashboard pages are actually used").option("--days <n>","window in days","30").option("--kind <kind>","cli | page (default: both)").option("--unused","list registered surfaces with ZERO recorded use instead").option("--json","raw JSON output").action(async e=>{let{listSurfaceUse:o}=await import("./surface-usage-CH3SHO77.js"),t=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=o({kind:t,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:i}=await import("./program-IAOEFLZP.js"),r=await i(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,u)=>{for(let f of d.commands??[]){let p=u?`${u} ${f.name()}`:f.name();c.push(p),l(f,p)}};l(r,"");let g=c.filter(d=>!a.has(d)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:g},null,2));return}console.log(),console.log(oe.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${oe.dim("\xB7")} ${d}`);console.log(),console.log(oe.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(oe.dim(" it must also fail the impact test. See docs/architecture/surface-reduction.md")),console.log();return}if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(),console.log(oe.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(oe.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(oe.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(oe.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=oe.dim(`${i.days}d`);console.log(` ${oe.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(oe.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as Ew}from"commander";import xe from"chalk";import{readFileSync as Aw}from"fs";import{resolve as Tw}from"path";te();var Qo=new Ew().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");Qo.command("serve",{isDefault:!0}).description("start the dashboard server (live view always; boards if configured)").option("--port <n>","override dashboard.port").option("--bind <host>","override dashboard.bind (e.g. 0.0.0.0)").action(async e=>{try{try{Ua(Tw(process.cwd(),".env"))}catch{}let o=jw(e.port,e.bind),{startBoardDashboard:t}=await import("./board-dashboard-MHMYOBKA.js");t(o)}catch(o){console.log(xe.red(` ${o.message}`)),process.env.DEBUG&&o.stack&&console.log(xe.dim(o.stack)),process.exit(1)}});function jw(e,o){try{let t=T();return e&&(t.dashboard.port=parseInt(e,10)),o&&(t.dashboard.bind=o),t}catch{return console.log(xe.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(xe.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
451
+ `}function zn(e,o,t=".env"){let n=ym(t),s=wm(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:o,raw:`${e}=${Br(o)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:o,raw:`${e}=${Br(o)}`})),tw(n,rw(s))}function Jr(e,o=".env"){return wm(o).find(s=>s.kind==="kv"&&s.key===e)?.value}var $m="https://t.me/BotFather";async function aw(e){try{let o=await fetch(`https://api.telegram.org/bot${e}/getMe`,{signal:AbortSignal.timeout(8e3)});if(!o.ok)return null;let t=await o.json();return t?.ok?t.result:null}catch{return null}}async function cw(e,o){let t=Date.now()+o,n=0;try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=-1&timeout=0`,{signal:AbortSignal.timeout(5e3)})).json();i?.result?.length&&(n=i.result[0].update_id+1)}catch{}for(;Date.now()<t;)try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=${n}&timeout=10`,{signal:AbortSignal.timeout(15e3)})).json();for(let r of i?.result||[]){n=Math.max(n,r.update_id+1);let a=r.message||r.edited_message||r.channel_post;if(a?.chat?.id)return{chatId:a.chat.id,chatTitle:a.chat.title||a.chat.username||a.chat.first_name,from:a.from?.first_name||a.from?.username||"unknown"}}}catch{}return null}async function bm(e={}){console.log(),console.log(ce.bold(" Connect Telegram")),console.log(),console.log(ce.dim(` 1. Open ${$m}`)),console.log(ce.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(ce.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{wantsBrowser:o}=await Vn({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});o&&at($m);let{token:t}=await Vn({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:b=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(b.trim())||"That doesn't look like a Telegram token"});t||(console.log(ce.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await aw(t.trim());n||(console.log(ce.red("\u2717 invalid or revoked")),process.exit(1)),console.log(ce.green(`\u2713 ${n.first_name} (@${n.username})`));let{readFileSync:s,existsSync:i}=await import("fs"),{resolve:r}=await import("path"),a=e.configPath||r(process.cwd(),"agentx.json");i(a)||(console.log(ce.red(` No agentx.json at ${a}. Run: agentx init`)),process.exit(1));let c=JSON.parse(s(a,"utf-8")),l=Object.keys(c.agents||{});l.length===0&&(console.log(ce.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await Vn({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map($=>({title:$,value:$})),initial:0})).agent),g||(console.log(ce.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},u=e.account||g;d[u]&&d[u].agentBinding!==g&&(u=(await Vn({type:"text",name:"account",message:`Account "${u}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:$=>/^[a-z0-9-]+$/i.test($)||"lowercase letters, digits, hyphens only"})).account),u||(console.log(ce.red(" Aborted")),process.exit(1));let f=`TG_${u.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;zn(f,t.trim()),process.env[f]=t.trim();let p=await re(b=>{Ie(b,"channels.telegram.enabled",!0),Ie(b,`channels.telegram.accounts.${u}`,{token:`\${${f}}`,agentBinding:g});let $=It(b,`agents.${g}.mentions`)||[],E=`@${n.username}`;$.includes(E)||($.push(E),Ie(b,`agents.${g}.mentions`,$))},{configPath:e.configPath});if(p.success||(console.log(ce.red(` \u2717 ${p.error}`)),process.exit(1)),console.log(),console.log(ce.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(ce.dim(` Token stored in .env as ${f}`)),console.log(ce.dim(` Mentions updated to include @${n.username}`)),p.reloaded?console.log(ce.dim(" Daemon hot-reloaded.")):console.log(ce.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:y}=await Vn({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!y)return;console.log(),console.log(ce.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(ce.dim(" Waiting up to 90s..."));let w=await cw(t.trim(),9e4);if(!w){console.log(ce.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(ce.dim(" agentx config set notifications.destination.channel telegram")),console.log(ce.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(ce.dim(` agentx config set notifications.destination.accountId ${u}`));return}let k=await re(b=>{Ie(b,"notifications.destination",{channel:"telegram",chatId:String(w.chatId),accountId:u})},{configPath:e.configPath});if(!k.success){console.log(ce.red(` \u2717 failed to save destination: ${k.error}`));return}console.log(ce.green(" \u2713 Default --notify target set")),console.log(ce.dim(` Chat: ${w.chatTitle||w.chatId} (from ${w.from})`)),console.log(ce.dim(" From now on, --notify me resolves to this chat.")),k.reloaded&&console.log(ce.dim(" Daemon hot-reloaded."))}import ve from"chalk";import Hr from"prompts";import{existsSync as zr,mkdirSync as lw,readdirSync as dw,readFileSync as km}from"fs";import{resolve as Gr}from"path";var gw=".agentx/whatsapp-sessions";function mw(){let e=Gr(process.cwd(),".agentx/daemon.pid");if(!zr(e))return!1;try{let o=parseInt(km(e,"utf-8").trim(),10);return o?(process.kill(o,0),!0):!1}catch{return!1}}function pw(e){if(!zr(e))return!1;try{return dw(e).some(o=>o.includes("creds")||o.endsWith(".json"))}catch{return!1}}async function uw(e,o){let t;try{t=await import("@whiskeysockets/baileys")}catch{return o(ve.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),o(ve.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=t.default||t;lw(e,{recursive:!0});let{state:i,saveCreds:r}=await s(e),a;try{a=(await t.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:i.creds,keys:t.makeCacheableSignalKeyStore?t.makeCacheableSignalKeyStore(i.keys,c):i.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",r),await new Promise(g=>{let u=setTimeout(()=>{o(ve.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}g(!1)},12e4);l.ev.on("connection.update",async f=>{if(f.qr){o(ve.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),o("");try{let{default:p}=await import("qrcode-terminal");p.generate(f.qr,{small:!0})}catch{o(` QR: ${f.qr}`)}o("")}if(f.connection==="open"){clearTimeout(u),o(ve.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(u),o(ve.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function vm(e={}){if(console.log(),console.log(ve.bold(" Connect WhatsApp")),console.log(),mw()){console.log(ve.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(ve.dim(" agentx daemon stop")),console.log();let{cont:l}=await Hr({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(ve.red(" Aborted")),process.exit(1))}let o=e.configPath||Gr(process.cwd(),"agentx.json");zr(o)||(console.log(ve.red(` No agentx.json at ${o}. Run: agentx init`)),process.exit(1));let t=JSON.parse(km(o,"utf-8")),n=e.sessionDir||t.channels?.whatsapp?.sessionDir||gw,s=Gr(process.cwd(),n),i=Object.keys(t.agents||{});i.length===0&&(console.log(ve.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await Hr({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(g=>({title:g,value:g})),initial:0})).agent),r||(console.log(ve.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(pw(s)&&a){let{keep:l}=await Hr({type:"confirm",name:"keep",message:`An existing session was found at ${n}. Keep it (recommended), or pair again?`,initial:!0});a=!l,l&&console.log(ve.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await uw(s,g=>console.log(g))||(console.log(ve.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await re(l=>{Ie(l,"channels.whatsapp.enabled",!0),Ie(l,"channels.whatsapp.sessionDir",n),Ie(l,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(ve.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(ve.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(ve.dim(` Session: ${n}`)),console.log(ve.dim(" Start the daemon to begin receiving:")),console.log(ve.dim(" agentx daemon start")),console.log(ve.dim(" Add routes later with:")),console.log(ve.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as fw}from"crypto";import je from"chalk";import xm from"prompts";var ri="agentx-mesh:",ai="//join/";function hw(e){return Buffer.from(e,"utf-8").toString("base64url")}function yw(e){return Buffer.from(e,"base64url").toString("utf-8")}function ww(e){return`${ri}${ai}${hw(JSON.stringify(e))}`}function $w(e){if(!e.startsWith(`${ri}${ai}`))throw new Error(`Not a mesh invite link \u2014 expected ${ri}${ai}\u2026`);let o=e.slice(ri.length+ai.length),t=JSON.parse(yw(o));if(t.version!==1)throw new Error(`Unsupported invite version: ${t.version}`);if(typeof t.url!="string"||typeof t.token!="string"||typeof t.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return t}function bw(){return fw(32).toString("hex")}function kw(e){let o=e?.node?.bind||"127.0.0.1:18800",[t,n]=o.split(":");return`http://${t}:${n}`}function vw(e){return e?.node?.name||e?.node?.id||"node"}async function Sm(e){let{readFileSync:o,existsSync:t}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");t(s)||(console.log(je.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(o(s,"utf-8")),r=Jr("MESH_TOKEN");r||(r=bw(),zn("MESH_TOKEN",r),console.log(je.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||kw(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await xm({type:"text",name:"url",message:"This node's URL as peers should reach it (e.g. http://100.x.x.x:18800):",initial:a,validate:u=>/^https?:\/\//.test(u)||"must start with http:// or https://"});d||(console.log(je.red(" Aborted")),process.exit(1)),a=d}let l=await re(d=>{Ie(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(je.red(` \u2717 ${l.error}`)),process.exit(1));let g=ww({url:a,token:r,name:vw(i),version:1});console.log(),console.log(je.bold(" Mesh invite")),console.log(),console.log(` ${je.cyan(g)}`),console.log(),console.log(je.dim(" Run on the other node:")),console.log(je.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(je.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function Em(e,o={}){let t;try{t=$w(e)}catch(i){console.log(je.red(` \u2717 ${i.message}`)),process.exit(1)}let n=Jr("MESH_TOKEN");if(n&&n!==t.token){let{overwrite:i}=await xm({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(je.red(" Aborted (keeping existing .env)")),process.exit(1))}zn("MESH_TOKEN",t.token);let s=await re(i=>{Ie(i,"mesh.enabled",!0);let r=It(i,"mesh.peers")||[],a=r.findIndex(l=>l.name===t.name),c={name:t.name,url:t.url,token:"${MESH_TOKEN}"};a>=0?r[a]=c:r.push(c),Ie(i,"mesh.peers",r)},{configPath:o.configPath});s.success||(console.log(je.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(je.green(" \u2713 Joined mesh")),console.log(je.dim(` Peer: ${t.name} @ ${t.url}`)),console.log(je.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(je.dim(" Daemon hot-reloaded.")):console.log(je.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let i=await fetch(`${t.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(i.ok){let r=await i.json(),a=Array.isArray(r.agents)?r.agents.length:"?";console.log(je.dim(` Reachable \u2014 ${t.name} exposes ${a} agents`))}else console.log(je.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(je.yellow(` Could not reach ${t.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var tn=new xw().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");tn.command("telegram").description("pair a Telegram bot \u2014 persists token in .env, binds to an agent, auto-detects default chat").option("--agent <id>","agent to bind the bot to (skips the prompt)").option("--account <name>","account label in channels.telegram.accounts (defaults to agent id)").option("--skip-chat-capture","don't listen for the first message after pairing").option("-c, --config <path>","path to agentx.json").action(async e=>{await bm({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});tn.command("whatsapp").description("pair WhatsApp via QR (prints in terminal), then writes channels.whatsapp config").option("--agent <id>","default agent for inbound messages").option("--session-dir <path>","session directory (default: .agentx/whatsapp-sessions)").option("--skip-pair","skip QR pairing (use when session already exists)").option("-c, --config <path>","path to agentx.json").action(async e=>{await vm({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var Am=tn.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");Am.command("invite").description("emit a single-use join link for another AgentX node").option("--url <url>","this node's URL as peers should reach it (Tailscale IP etc.)").option("-c, --config <path>","path to agentx.json").action(async e=>{await Sm({url:e.url,configPath:e.config})});Am.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(e,o)=>{await Em(e,{configPath:o.config})});tn.action(()=>{console.log(),console.log(on.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${on.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${on.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${on.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${on.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(on.dim(" GitLab connect is the next slice.")),console.log()});te();import{Command as Sw}from"commander";import oe from"chalk";var nn=new Sw().name("usage").description("token usage analysis and reporting");nn.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=T(),[o,t]=e.node.bind.split(":"),s=await(await fetch(`http://${o||"127.0.0.1"}:${t}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(oe.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(oe.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${oe.bold(i(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${i(s.totalInput)}`),console.log(` Output: ${i(s.totalOutput)}`),console.log(` Cache read: ${i(s.totalCacheRead)}`),console.log(` Cache create: ${i(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${oe.red(String(s.totalErrors))}`),console.log(),console.log(oe.bold(" By Agent:"));let r=Object.entries(s.byAgent||{});r.sort((a,c)=>c[1].total-a[1].total);for(let[a,c]of r){let l=i(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${oe.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${oe.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(oe.red(" Daemon not running. Start with: agentx daemon start")):console.log(oe.red(` ${e.message}`))}});nn.command("plan").description("show the Claude plan windows as Claude Code last reported them, and any hold on fresh sessions").option("--lift","lift the hold on fresh sessions now, without waiting for the reset time").option("--json","raw JSON output").action(async e=>{try{let o=T(),[t,n]=o.node.bind.split(":"),s=`http://${t||"127.0.0.1"}:${n}`,i=e.lift?await fetch(`${s}/usage/plan/lift`,{method:"POST",signal:AbortSignal.timeout(3e3)}):await fetch(`${s}/usage/plan`,{signal:AbortSignal.timeout(3e3)});if(!i.ok)throw new Error(`Daemon answered ${i.status}. It may be older than this command; restart it.`);let r=await i.json();if(e.json){console.log(JSON.stringify(r,null,2));return}let a=d=>d.replace(/_/g," ");if(console.log(),e.lift){let d=r.lifted.map(u=>a(u.window));console.log(d.length?` Lifted the hold on: ${d.join(", ")}. The next fresh session asks Claude again.`:oe.dim(" No hold to lift.")),console.log();return}let c=r.now,l=new Set(r.holds.map(d=>d.window));console.log(oe.bold(" Claude plan (as Claude Code last reported it)")),console.log(),r.provider.length===0&&console.log(oe.dim(" No report yet. Claude Code reports on each turn; the list is empty after a daemon restart."));for(let d of r.provider){let u=d.usingOverage?"extra usage":d.status==="allowed_warning"?"nearly full":d.status,f=typeof d.utilization=="number"?`${Math.round(d.utilization*100)}% used`:"",p=Math.max(1,Math.round((d.resetsAt-c)/6e4)),y=d.resetsAt>c?p<60?`resets in ${p} min`:p<48*60?`resets in ${Math.round(p/60)} h`:`resets in ${Math.round(p/1440)} days`:"",w=l.has(d.window)?oe.red("holding fresh sessions"):"";console.log(` ${a(d.window).padEnd(18)} ${u.padEnd(12)} ${[f,y,w].filter(Boolean).join(", ")}`)}console.log();let g=d=>d?` of ${d}`:"";console.log(` Fresh sessions started: ${r.lastHour}${g(r.maxPerHour)} in the last hour, ${r.last5h}${g(r.maxPer5h)} in the last 5 hours`),l.size&&console.log(oe.dim(" To try again now: agentx usage plan --lift")),console.log()}catch(o){o.cause?.code==="ECONNREFUSED"?console.log(oe.red(" Daemon not running. Start with: agentx daemon start")):console.log(oe.red(` ${o.message}`))}});nn.command("report").description("run full session analysis (parses Claude Code JSONL files)").option("--days <n>","analyze last N days","7").action(async e=>{let{execSync:o}=await import("child_process"),{existsSync:t}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!t(s)){console.log(oe.red(` Script not found: ${s}`)),console.log(oe.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(oe.dim(" Analyzing Claude Code sessions..."));try{o(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(oe.red(" Analysis failed. Is Python 3 installed?"))}});nn.command("surfaces").description("which CLI commands and dashboard pages are actually used").option("--days <n>","window in days","30").option("--kind <kind>","cli | page (default: both)").option("--unused","list registered surfaces with ZERO recorded use instead").option("--json","raw JSON output").action(async e=>{let{listSurfaceUse:o}=await import("./surface-usage-CH3SHO77.js"),t=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=o({kind:t,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:i}=await import("./program-RO5BWG6I.js"),r=await i(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,u)=>{for(let f of d.commands??[]){let p=u?`${u} ${f.name()}`:f.name();c.push(p),l(f,p)}};l(r,"");let g=c.filter(d=>!a.has(d)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:g},null,2));return}console.log(),console.log(oe.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${oe.dim("\xB7")} ${d}`);console.log(),console.log(oe.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(oe.dim(" it must also fail the impact test. See docs/architecture/surface-reduction.md")),console.log();return}if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(),console.log(oe.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(oe.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(oe.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(oe.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=oe.dim(`${i.days}d`);console.log(` ${oe.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(oe.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as Ew}from"commander";import xe from"chalk";import{readFileSync as Aw}from"fs";import{resolve as Tw}from"path";te();var Qo=new Ew().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");Qo.command("serve",{isDefault:!0}).description("start the dashboard server (live view always; boards if configured)").option("--port <n>","override dashboard.port").option("--bind <host>","override dashboard.bind (e.g. 0.0.0.0)").action(async e=>{try{try{Ua(Tw(process.cwd(),".env"))}catch{}let o=jw(e.port,e.bind),{startBoardDashboard:t}=await import("./board-dashboard-MHMYOBKA.js");t(o)}catch(o){console.log(xe.red(` ${o.message}`)),process.env.DEBUG&&o.stack&&console.log(xe.dim(o.stack)),process.exit(1)}});function jw(e,o){try{let t=T();return e&&(t.dashboard.port=parseInt(e,10)),o&&(t.dashboard.bind=o),t}catch{return console.log(xe.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(xe.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
452
452
  `)),{node:{id:"setup",name:"Setup",bind:"127.0.0.1:18800"},providers:{},agents:{},channels:{},crons:{},mesh:{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},boards:[],dashboard:{enabled:!0,port:e?parseInt(e,10):4202,bind:o||"127.0.0.1",daemonUrl:"http://localhost:18800",daemons:[]},business:void 0,session:{staleMinutes:120}}}}Qo.command("list").description("list configured boards").action(()=>{try{let e=T();if(!e.boards?.length){console.log(xe.dim(`
453
453
  No boards configured.
454
454
  `));return}console.log();for(let o of e.boards){console.log(` ${xe.cyan(o.id)} \u2014 ${o.name}`);let t=o.source;console.log(xe.dim(` source: ${t.type}${t.projects?" ("+t.projects.join(", ")+")":""}`)),o.primaryToolLabel&&console.log(xe.dim(` primary label: ${o.primaryToolLabel}`)),console.log(xe.dim(` window: ${o.timeRangeDays} days`))}console.log()}catch(e){console.log(xe.red(` ${e.message}`)),process.exit(1)}});Qo.command("add <id>").description("add a GitLab board to agentx.json").requiredOption("--name <name>","human-readable board name").requiredOption("--projects <paths>","comma-separated GitLab project paths (e.g. 'globex/system,globex/website')").option("--label <label>","primary tool label ANDed into every query (e.g. 'Tool::Claude')").option("--days <n>","open-window time range in days","30").option("--closed-days <n>","closed-window in days","30").action((e,o)=>{try{Yn(t=>{if(Array.isArray(t.boards)||(t.boards=[]),t.boards.find(i=>i.id===e))throw new Error(`board "${e}" already exists`);let n=String(o.projects).split(",").map(i=>i.trim()).filter(Boolean);if(n.length===0)throw new Error("--projects must include at least one path");let s={id:e,name:o.name,source:{type:"gitlab",projects:n},timeRangeDays:parseInt(o.days,10)||30,closedWindowDays:parseInt(o.closedDays,10)||30};return o.label&&(s.primaryToolLabel=o.label),t.boards.push(s),`added board "${e}" (${n.join(", ")})`})}catch(t){console.log(xe.red(` ${t.message}`)),process.exit(1)}});Qo.command("edit <id>").description("edit board fields without re-creating it").option("--name <name>","rename").option("--projects <paths>","comma-separated GitLab project paths (replaces the list)").option("--label <label>","primary tool label (set to '-' to clear)").option("--days <n>","open-window time range in days").option("--closed-days <n>","closed-window in days").action((e,o)=>{try{Yn(t=>{let s=(Array.isArray(t.boards)?t.boards:[]).find(r=>r.id===e);if(!s)throw new Error(`board "${e}" not found`);let i=[];if(o.name&&(s.name=o.name,i.push(`name="${o.name}"`)),o.projects){let r=String(o.projects).split(",").map(a=>a.trim()).filter(Boolean);if(r.length===0)throw new Error("--projects must include at least one path");s.source={...s.source||{type:"gitlab"},type:"gitlab",projects:r},i.push(`projects=${r.length}`)}if(o.label!==void 0&&(o.label==="-"?(delete s.primaryToolLabel,i.push("label cleared")):(s.primaryToolLabel=o.label,i.push(`label="${o.label}"`))),o.days&&(s.timeRangeDays=parseInt(o.days,10)||s.timeRangeDays,i.push(`days=${s.timeRangeDays}`)),o.closedDays&&(s.closedWindowDays=parseInt(o.closedDays,10)||s.closedWindowDays,i.push(`closed-days=${s.closedWindowDays}`)),i.length===0)throw new Error("no changes \u2014 pass at least one option");return`board "${e}" updated (${i.join(", ")})`})}catch(t){console.log(xe.red(` ${t.message}`)),process.exit(1)}});var Vr=Qo.command("column").description("manage a board's columns (add / remove / edit / list)");Vr.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let t=(JSON.parse(Aw("agentx.json","utf-8")).boards||[]).find(s=>s.id===e);if(!t)throw new Error(`board "${e}" not found`);let n=t.columns||[];if(n.length===0){console.log(xe.dim(" no columns (board falls back to GitLab default flow)"));return}for(let s of n){let i=s.kind==="scoped-label"?`scoped="${s.scopedLabel}"`:s.kind==="label"?`label="${s.mapsToLabel||""}"`:s.kind==="open-backlog"?`prefix="${s.scopedPrefix}"`:s.kind;console.log(` ${xe.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${xe.dim(i)}`)}}catch(o){console.log(xe.red(` ${o.message}`)),process.exit(1)}});Vr.command("add <boardId> <columnId>").description("add a column to a board").requiredOption("--title <title>","column title").option("--kind <kind>","open-backlog | scoped-label | closed | label","scoped-label").option("--scoped <label>","for kind=scoped-label, the full label (e.g. 'Status::Doing')").option("--label <label>","for kind=label, the label name to add/remove").option("--scoped-prefix <prefix>","for kind=open-backlog/scoped-label","Status").option("--accent <color>","hex/CSS color for the column accent bar").action((e,o,t)=>{try{Yn(n=>{let i=(Array.isArray(n.boards)?n.boards:[]).find(a=>a.id===e);if(!i)throw new Error(`board "${e}" not found`);if(i.columns=i.columns||[],i.columns.find(a=>a.id===o))throw new Error(`column "${o}" already exists on board "${e}"`);let r={id:o,title:t.title,kind:t.kind,scopedPrefix:t.scopedPrefix};if(t.kind==="scoped-label"){if(!t.scoped)throw new Error("--scoped required for kind=scoped-label");r.scopedLabel=t.scoped}if(t.kind==="label"){if(!t.label)throw new Error("--label required for kind=label");r.mapsToLabel=t.label}return t.accent&&(r.accent=t.accent),i.columns.push(r),`column "${o}" added to board "${e}"`})}catch(n){console.log(xe.red(` ${n.message}`)),process.exit(1)}});Vr.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,o)=>{try{Yn(t=>{let s=(Array.isArray(t.boards)?t.boards:[]).find(r=>r.id===e);if(!s)throw new Error(`board "${e}" not found`);let i=(s.columns||[]).length;if(s.columns=(s.columns||[]).filter(r=>r.id!==o),s.columns.length===i)throw new Error(`column "${o}" not found`);return`column "${o}" removed from board "${e}"`})}catch(t){console.log(xe.red(` ${t.message}`)),process.exit(1)}});Qo.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{Yn(o=>{if(!Array.isArray(o.boards)||o.boards.length===0)throw new Error("no boards configured");let t=o.boards.length;if(o.boards=o.boards.filter(n=>n.id!==e),o.boards.length===t)throw new Error(`board "${e}" not found`);return`removed board "${e}"`})}catch(o){console.log(xe.red(` ${o.message}`)),process.exit(1)}});function Yn(e){let{summary:o,backupPath:t}=to(n=>e(n));console.log(xe.green(`
@@ -675,7 +675,7 @@ Restart the daemon to activate.
675
675
  dist/
676
676
  *.log
677
677
  .env
678
- `}import{Command as $b}from"commander";import Pe from"chalk";import{writeFileSync as bb,mkdirSync as kb,existsSync as Si,readFileSync as vp,appendFileSync as xp}from"fs";import{resolve as yn,dirname as Ap}from"path";import{homedir as ha}from"os";var Tp=new $b().name("completion").description("generate a shell completion script for agentx").option("-s, --shell <shell>","shell to generate completion for: zsh|bash|fish","zsh").option("-i, --install","install the completion script to a default path for the shell").option("-o, --output <path>","write the script to this path (overrides default install path)").option("-y, --yes","skip confirmation prompts (non-interactive)").action(async e=>{let{buildProgram:o}=await import("./program-IAOEFLZP.js"),t=await o(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=Sb(t);break;case"bash":s=Ob(t);break;case"fish":s=Cb(t);break;default:console.error(Pe.red(`unsupported shell: ${n}`)),console.error(Pe.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let i=e.output?yn(String(e.output)):vb(n);kb(Ap(i),{recursive:!0}),bb(i,s),console.log(Pe.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${i}`),console.log(),xb(n,i,!!e.yes)});function vb(e){let o=ha();switch(e){case"zsh":return yn(o,".zsh","completions","_agentx");case"bash":return yn(o,".bash_completion.d","agentx.bash");case"fish":return yn(o,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function xb(e,o,t){if(e==="zsh"){let n=yn(ha(),".zshrc"),s=Ap(o),i=`fpath=(${s} $fpath)`,r="autoload -U compinit && compinit",a=Si(n)?vp(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(Pe.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(t&&Si(n)){let g=["","# agentx completion"];c&&g.push(i),l&&g.push(r),xp(n,g.join(`
678
+ `}import{Command as $b}from"commander";import Pe from"chalk";import{writeFileSync as bb,mkdirSync as kb,existsSync as Si,readFileSync as vp,appendFileSync as xp}from"fs";import{resolve as yn,dirname as Ap}from"path";import{homedir as ha}from"os";var Tp=new $b().name("completion").description("generate a shell completion script for agentx").option("-s, --shell <shell>","shell to generate completion for: zsh|bash|fish","zsh").option("-i, --install","install the completion script to a default path for the shell").option("-o, --output <path>","write the script to this path (overrides default install path)").option("-y, --yes","skip confirmation prompts (non-interactive)").action(async e=>{let{buildProgram:o}=await import("./program-RO5BWG6I.js"),t=await o(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=Sb(t);break;case"bash":s=Ob(t);break;case"fish":s=Cb(t);break;default:console.error(Pe.red(`unsupported shell: ${n}`)),console.error(Pe.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let i=e.output?yn(String(e.output)):vb(n);kb(Ap(i),{recursive:!0}),bb(i,s),console.log(Pe.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${i}`),console.log(),xb(n,i,!!e.yes)});function vb(e){let o=ha();switch(e){case"zsh":return yn(o,".zsh","completions","_agentx");case"bash":return yn(o,".bash_completion.d","agentx.bash");case"fish":return yn(o,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function xb(e,o,t){if(e==="zsh"){let n=yn(ha(),".zshrc"),s=Ap(o),i=`fpath=(${s} $fpath)`,r="autoload -U compinit && compinit",a=Si(n)?vp(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(Pe.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(t&&Si(n)){let g=["","# agentx completion"];c&&g.push(i),l&&g.push(r),xp(n,g.join(`
679
679
  `)+`
680
680
  `),console.log(Pe.green("\u2713 Patched ~/.zshrc")),console.log(Pe.dim("Reload your shell: exec zsh"));return}console.log(Pe.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(Pe.cyan(` ${i}`)),l&&console.log(Pe.cyan(` ${r}`)),console.log(),console.log(Pe.dim("Then reload: exec zsh")),console.log(Pe.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=yn(ha(),".bashrc"),s=`[ -f "${o}" ] && source "${o}"`;if((Si(n)?vp(n,"utf-8"):"").includes(o)){console.log(Pe.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(t&&Si(n)){xp(n,`
681
681
  # agentx completion
@@ -691,4 +691,4 @@ ${Ib({...o,category:e.category})}`),g&&a.set(l.id,g)}let c=`https://github.com/$
691
691
  ${t.url}`)}catch(o){console.error($n.red(` ${o.message}`)),process.exitCode=1}});rs.command("draft <file>").description("turn a draft JSON file ({category, title, fields}) into a pre-filled issue form link; '-' reads stdin").requiredOption("--model <model>","the model that wrote the draft").option("--models <pathOrUrl>","model list to read",wa).action(async(e,o)=>{try{let t=await ka(o.models);if(!$a(o.model,t)){console.log(ba(o.model,t)),process.exitCode=1;return}let n=e==="-"?await _b():await Rb(e,"utf8"),s=JSON.parse(n),{version:i}=await ps(),r=Ip({...s,fields:s.fields??{}},{model:o.model,version:i??"unknown"});console.log(r)}catch(t){console.error($n.red(` ${t.message}`)),process.exitCode=1}});async function _b(){let e=[];for await(let o of process.stdin)e.push(o);return Buffer.concat(e).toString("utf8")}async function nI(){let e=await ps(),o=new Db().name("agentx").description("self-hosted multi-agent orchestrator \u2014 Telegram, WhatsApp, crons, A2A mesh, wiki knowledge").version(e.version||"1.0.0","-v, --version","display the version number");o.hook("preAction",(t,n)=>{let s=Vl(n);Yl(s)&&zl("cli",s)});for(let t of[Ed,Sd,tn,Mt,Ut,ro,Ml,ct,Ms,Co,No,Zt,hm,Xo,Ps,ep,Vo,Gd,og,Wn,mg,hg,$g,vg,xg,Ug,Jg,Hg,ht,nn,ip,_n,Bo,Tp,rs])o.addCommand(t);for(let t of Rp)o.addCommand(t,{hidden:!0});return o.addHelpText("after",()=>{let t=Rp.map(n=>n.name()).sort();return["",`Advanced (${t.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,Pb(t,74," "),""].join(`
692
692
  `)}),o}var Rp=[ne,an,ot,$o,Mn,Kt,Ke,_o,Qo,yt,gn,mn,Go,Ge,Jt,ni,Xm,Qm,Oo,no,ed,dt,ss,ur,et,Ze,Wt,fr,yi,Ao,Do,fp,yp,sp];function Pb(e,o,t){let n=[],s="";for(let i of e)s&&s.length+i.length+2>o&&(n.push(t+s),s=""),s+=(s?", ":"")+i;return s&&n.push(t+s),n.join(`
693
693
  `)}export{nI as buildProgram};
694
- //# sourceMappingURL=program-IAOEFLZP.js.map
694
+ //# sourceMappingURL=program-RO5BWG6I.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agentix-cli",
3
- "version": "0.92.4",
3
+ "version": "0.93.0",
4
4
  "description": "AI operations layer for small and medium businesses. Routes Telegram, WhatsApp, GitLab, GitHub, crons, webhooks, and mesh tasks to AI agents. Web wizard for operators, CLI for engineers. Self-hosted.",
5
5
  "license": "MIT",
6
6
  "author": {