agentix-cli 0.50.1 → 0.52.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/apps/mac-voice/Sources/AgentXVoice/AgentClient.swift +67 -14
- package/apps/mac-voice/Sources/AgentXVoice/Config.swift +20 -3
- package/apps/mac-voice/Sources/AgentXVoice/Panel.swift +24 -31
- package/apps/mac-voice/Sources/AgentXVoice/Speech.swift +16 -2
- package/apps/mac-voice/Sources/AgentXVoice/StatusMenu.swift +173 -0
- package/apps/mac-voice/Sources/AgentXVoice/main.swift +62 -15
- package/dist/{App-TDUUFVDV.js → App-QVNQ5BQK.js} +2 -2
- package/dist/{ChatApp-IOWDXM3R.js → ChatApp-CC57XC23.js} +2 -2
- package/dist/{agent-KRLAT3YJ.js → agent-ILH6ANOM.js} +2 -2
- package/dist/{board-dashboard-VA4VSCMQ.js → board-dashboard-WG4ZZV4A.js} +346 -137
- package/dist/board-dashboard-WG4ZZV4A.js.map +1 -0
- package/dist/{chunk-ZWGRRFJI.js → chunk-2KQTE4XI.js} +2 -2
- package/dist/{chunk-A6IV2VQY.js → chunk-6HAZ6YWI.js} +2 -2
- package/dist/{chunk-WUDXUY7H.js → chunk-BNVF66YL.js} +3 -3
- package/dist/chunk-BNVF66YL.js.map +1 -0
- package/dist/{chunk-HHY3MSMN.js → chunk-CAA546XN.js} +2 -2
- package/dist/{chunk-X5K3HR4V.js → chunk-F7WY24UZ.js} +2 -2
- package/dist/{chunk-7WDJW37G.js → chunk-GUJB53QU.js} +2 -2
- package/dist/{chunk-FDYGTQVW.js → chunk-H2TWRZC2.js} +2 -2
- package/dist/{chunk-F2PEUQW4.js → chunk-JQR3NTHI.js} +2 -2
- package/dist/{chunk-4BNQSUWV.js → chunk-KAFO5QZR.js} +2 -2
- package/dist/{chunk-ZQSB6IX4.js → chunk-KFALP5NO.js} +2 -2
- package/dist/{chunk-RP7GLXOA.js → chunk-NTG5ZXRI.js} +180 -179
- package/dist/chunk-NTG5ZXRI.js.map +1 -0
- package/dist/{chunk-2BRX2EMT.js → chunk-PSDCRZZM.js} +2 -2
- package/dist/{chunk-BVRUDRCM.js → chunk-QP6XNTBB.js} +2 -2
- package/dist/{chunk-AVJRATR5.js → chunk-ROCUOXCW.js} +2 -2
- package/dist/{chunk-FULEQYM6.js → chunk-S7CVSKOX.js} +2 -2
- package/dist/chunk-S7CVSKOX.js.map +1 -0
- package/dist/{chunk-XSFXAJDA.js → chunk-SRCXUZM2.js} +4 -4
- package/dist/{chunk-XSFXAJDA.js.map → chunk-SRCXUZM2.js.map} +1 -1
- package/dist/chunk-U67EG5IF.js +19 -0
- package/dist/chunk-U67EG5IF.js.map +1 -0
- package/dist/{chunk-JWLTI6NZ.js → chunk-UL4E2CV4.js} +163 -160
- package/dist/chunk-UL4E2CV4.js.map +1 -0
- package/dist/chunk-V7XZN3MQ.js +123 -0
- package/dist/chunk-V7XZN3MQ.js.map +1 -0
- package/dist/{chunk-WW6KNRIR.js → chunk-VMS3HVTT.js} +2 -2
- package/dist/{chunk-5KCOH5FQ.js → chunk-WDQ3BPFS.js} +2 -2
- package/dist/{chunk-ZN7637EF.js → chunk-XZTR5MBJ.js} +2 -2
- package/dist/chunk-YE2BUU3Z.js +28 -0
- package/dist/chunk-YE2BUU3Z.js.map +1 -0
- package/dist/{chunk-ZKDWQJVS.js → chunk-YEV6W34S.js} +55 -55
- package/dist/{chunk-ZKDWQJVS.js.map → chunk-YEV6W34S.js.map} +1 -1
- package/dist/cli.js +1 -1
- package/dist/client-I7GAAM3T.js +2 -0
- package/dist/{config-I4GWI22T.js → config-TVW7UCKG.js} +2 -2
- package/dist/config-mutator-JHM53P5A.js +2 -0
- package/dist/doctor-CXFMV6PT.js +2 -0
- package/dist/index.d.ts +256 -6
- package/dist/index.js +1 -1
- package/dist/processes-NNXSRQSV.js +2 -0
- package/dist/program-UXJWH5JG.js +2 -0
- package/dist/{promote-EDEG2HQR.js → promote-4T64VW5K.js} +2 -2
- package/dist/query-6IKL52WT.js +2 -0
- package/dist/registry-E4QUXHMQ.js +2 -0
- package/dist/{request-planner-JDBXFNQ4.js → request-planner-BRLDCYU5.js} +2 -2
- package/dist/{review-candidates-EBP5CFOB.js → review-candidates-QWW5PDUU.js} +2 -2
- package/dist/{routing-Q2EOZ3VW.js → routing-DP6S7OJL.js} +2 -2
- package/dist/schedule-tool-TPJ6GR47.js +2 -0
- package/dist/scheduler-7QPG6OTY.js +2 -0
- package/dist/{seat-LV3STEXI.js → seat-3KUNRM5Z.js} +2 -2
- package/dist/{select-5NHY4T5A.js → select-ILXHYJGD.js} +2 -2
- package/dist/{tool-2RKPJWDG.js → tool-SF3BCY55.js} +2 -2
- package/dist/wiki-WETANN3W.js +2 -0
- package/package.json +1 -1
- package/dist/board-dashboard-VA4VSCMQ.js.map +0 -1
- package/dist/chunk-FULEQYM6.js.map +0 -1
- package/dist/chunk-JUJ3TCOE.js +0 -19
- package/dist/chunk-JUJ3TCOE.js.map +0 -1
- package/dist/chunk-JWLTI6NZ.js.map +0 -1
- package/dist/chunk-JY7POTMB.js +0 -123
- package/dist/chunk-JY7POTMB.js.map +0 -1
- package/dist/chunk-KH6L7GDO.js +0 -28
- package/dist/chunk-KH6L7GDO.js.map +0 -1
- package/dist/chunk-RP7GLXOA.js.map +0 -1
- package/dist/chunk-WUDXUY7H.js.map +0 -1
- package/dist/client-PC7OEKSK.js +0 -2
- package/dist/config-mutator-3RFKH3OV.js +0 -2
- package/dist/doctor-OG6DK52Y.js +0 -2
- package/dist/processes-CMTMB7LG.js +0 -2
- package/dist/program-RFAHI4SS.js +0 -2
- package/dist/query-P5LMGXVS.js +0 -2
- package/dist/registry-GJLY5J5E.js +0 -2
- package/dist/schedule-tool-N2Z5E6AR.js +0 -2
- package/dist/scheduler-WTPERNYJ.js +0 -2
- package/dist/wiki-XQMJ2FPU.js +0 -2
- /package/dist/{App-TDUUFVDV.js.map → App-QVNQ5BQK.js.map} +0 -0
- /package/dist/{ChatApp-IOWDXM3R.js.map → ChatApp-CC57XC23.js.map} +0 -0
- /package/dist/{agent-KRLAT3YJ.js.map → agent-ILH6ANOM.js.map} +0 -0
- /package/dist/{chunk-ZWGRRFJI.js.map → chunk-2KQTE4XI.js.map} +0 -0
- /package/dist/{chunk-A6IV2VQY.js.map → chunk-6HAZ6YWI.js.map} +0 -0
- /package/dist/{chunk-HHY3MSMN.js.map → chunk-CAA546XN.js.map} +0 -0
- /package/dist/{chunk-X5K3HR4V.js.map → chunk-F7WY24UZ.js.map} +0 -0
- /package/dist/{chunk-7WDJW37G.js.map → chunk-GUJB53QU.js.map} +0 -0
- /package/dist/{chunk-FDYGTQVW.js.map → chunk-H2TWRZC2.js.map} +0 -0
- /package/dist/{chunk-F2PEUQW4.js.map → chunk-JQR3NTHI.js.map} +0 -0
- /package/dist/{chunk-4BNQSUWV.js.map → chunk-KAFO5QZR.js.map} +0 -0
- /package/dist/{chunk-ZQSB6IX4.js.map → chunk-KFALP5NO.js.map} +0 -0
- /package/dist/{chunk-2BRX2EMT.js.map → chunk-PSDCRZZM.js.map} +0 -0
- /package/dist/{chunk-BVRUDRCM.js.map → chunk-QP6XNTBB.js.map} +0 -0
- /package/dist/{chunk-AVJRATR5.js.map → chunk-ROCUOXCW.js.map} +0 -0
- /package/dist/{chunk-WW6KNRIR.js.map → chunk-VMS3HVTT.js.map} +0 -0
- /package/dist/{chunk-5KCOH5FQ.js.map → chunk-WDQ3BPFS.js.map} +0 -0
- /package/dist/{chunk-ZN7637EF.js.map → chunk-XZTR5MBJ.js.map} +0 -0
- /package/dist/{client-PC7OEKSK.js.map → client-I7GAAM3T.js.map} +0 -0
- /package/dist/{config-I4GWI22T.js.map → config-TVW7UCKG.js.map} +0 -0
- /package/dist/{config-mutator-3RFKH3OV.js.map → config-mutator-JHM53P5A.js.map} +0 -0
- /package/dist/{doctor-OG6DK52Y.js.map → doctor-CXFMV6PT.js.map} +0 -0
- /package/dist/{processes-CMTMB7LG.js.map → processes-NNXSRQSV.js.map} +0 -0
- /package/dist/{program-RFAHI4SS.js.map → program-UXJWH5JG.js.map} +0 -0
- /package/dist/{promote-EDEG2HQR.js.map → promote-4T64VW5K.js.map} +0 -0
- /package/dist/{query-P5LMGXVS.js.map → query-6IKL52WT.js.map} +0 -0
- /package/dist/{registry-GJLY5J5E.js.map → registry-E4QUXHMQ.js.map} +0 -0
- /package/dist/{request-planner-JDBXFNQ4.js.map → request-planner-BRLDCYU5.js.map} +0 -0
- /package/dist/{review-candidates-EBP5CFOB.js.map → review-candidates-QWW5PDUU.js.map} +0 -0
- /package/dist/{routing-Q2EOZ3VW.js.map → routing-DP6S7OJL.js.map} +0 -0
- /package/dist/{schedule-tool-N2Z5E6AR.js.map → schedule-tool-TPJ6GR47.js.map} +0 -0
- /package/dist/{scheduler-WTPERNYJ.js.map → scheduler-7QPG6OTY.js.map} +0 -0
- /package/dist/{seat-LV3STEXI.js.map → seat-3KUNRM5Z.js.map} +0 -0
- /package/dist/{select-5NHY4T5A.js.map → select-ILXHYJGD.js.map} +0 -0
- /package/dist/{tool-2RKPJWDG.js.map → tool-SF3BCY55.js.map} +0 -0
- /package/dist/{wiki-XQMJ2FPU.js.map → wiki-WETANN3W.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/desktop/install.ts","../src/notify/local.ts"],"sourcesContent":["import { existsSync, readFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nexport const DESKTOP_LABEL = 'tn.acme.agentx.voice'\nexport const DESKTOP_APP = 'AgentX Desktop.app'\nexport const HELPER_APP = 'AgentX Helper.app'\nexport function desktopPlatformError(platform: string, arch: string, release: string): string | null {\n if (platform !== 'darwin' || arch !== 'arm64' || Number(release.split('.')[0]) < 23)\n return 'AgentX Desktop currently requires Apple Silicon and macOS 14 or newer.'\n return null\n}\nexport function selectDesktopAgent(agents: Record<string, unknown>, requested?: string): string {\n if (requested && !Object.hasOwn(agents, requested)) throw new Error(`Unknown agent: ${requested}. Run agentx agent list.`)\n const id = requested || Object.keys(agents)[0]\n if (!id) throw new Error('No agents configured. Run agentx setup first.')\n return id\n}\nexport function shellQuote(value: string): string { return `'${value.replace(/'/g, \"'\\\\''\")}'` }\n/** launchd's default PATH, which is all a login item gets unless the plist sets one. */\nexport const LAUNCHD_PATH = '/usr/bin:/bin:/usr/sbin:/sbin'\n/** PATH for the login item: AGENTX_VOICE_PATH when set, else the folder of\n * the ffmpeg found at install time (mlx_whisper needs it) ahead of launchd's default. */\nexport function desktopPath(ffmpeg: string | null, override?: string): string {\n if (override) return override\n return [...new Set([...(ffmpeg ? [dirname(ffmpeg)] : []), ...LAUNCHD_PATH.split(':')])].join(':')\n}\n/** The PATH a login item plist sets, or launchd's default when it sets none. */\nexport function plistPathEnv(plist: string): string {\n const m = plist.match(/<key>PATH<\\/key>\\s*<string>([^<]*)<\\/string>/)\n if (!m) return LAUNCHD_PATH\n const ents: Record<string, string> = { amp: '&', lt: '<', gt: '>', quot: '\"', apos: \"'\" }\n return m[1].replace(/&(amp|lt|gt|quot|apos);/g, (_, e) => ents[e])\n}\n/** The file that a process with this PATH would run, or null. */\nexport function findOnPath(bin: string, path: string, isExecutable: (file: string) => boolean): string | null {\n for (const dir of path.split(':')) if (dir && isExecutable(join(dir, bin))) return join(dir, bin)\n return null\n}\nexport function desktopPlist(opts: { executable: string; cwd: string; agent: string; url: string; helper: string; cli: string; node: string; log: string; path: string }): string {\n const xml = (s: string) => s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/\"/g, '"').replace(/'/g, ''')\n const env = {\n PATH: opts.path,\n AGENTX_VOICE_AGENT: opts.agent,\n AGENTX_DAEMON_URL: opts.url,\n AGENTX_MAC_HELPER: opts.helper,\n AGENTX_PASTE_COMMAND: `cd ${shellQuote(opts.cwd)} && ${shellQuote(opts.node)} ${shellQuote(opts.cli)} paste`,\n }\n return `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\"><dict>\n<key>Label</key><string>${DESKTOP_LABEL}</string>\n<key>ProgramArguments</key><array><string>${xml(opts.executable)}</string></array>\n<key>WorkingDirectory</key><string>${xml(opts.cwd)}</string>\n<key>EnvironmentVariables</key><dict>${Object.entries(env).map(([k,v]) => `<key>${k}</key><string>${xml(v)}</string>`).join('')}</dict>\n<key>RunAtLoad</key><true/><key>KeepAlive</key><true/>\n<key>ProcessType</key><string>Interactive</string>\n<key>StandardErrorPath</key><string>${xml(opts.log)}</string>\n</dict></plist>\\n`\n}\n/** build.sh arguments for the helper: the banner icon from\n * notifications.local.icon, or none for the bundled AgentX logo. */\nexport function helperBuildArgs(icon?: string): string[] {\n return icon ? ['--icon', icon] : []\n}\nexport function installedHelper(home: string): string {\n return join(home, 'Applications', HELPER_APP, 'Contents/MacOS/agentx-mac-helper')\n}\n/** The AgentX package folder, found by walking up from this file (dist/\n * when installed, src/ in a checkout) — never from the caller's cwd, so\n * `agentx notify` finds a repo-built helper from any folder. */\nexport function packageRoot(from = dirname(fileURLToPath(import.meta.url))): string | null {\n for (let dir = from; ; dir = dirname(dir)) {\n try {\n if (JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')).name === 'agentix-cli') return dir\n } catch { /* no package.json here — keep walking up */ }\n if (dirname(dir) === dir) return null\n }\n}\n/** The helper to run: an explicit path, else the one `agentx desktop\n * install` put in ~/Applications, else one built in the package. */\nexport function resolveHelper(root: string | null, home: string, override?: string): string {\n if (override) return override\n const installed = installedHelper(home)\n if (existsSync(installed) || !root) return installed\n return join(root, 'apps/mac-helper/build', HELPER_APP, 'Contents/MacOS/agentx-mac-helper')\n}\n","import { execFile } from \"child_process\"\nimport { existsSync } from \"fs\"\nimport { homedir } from \"os\"\nimport { isAbsolute } from \"path\"\nimport { packageRoot, resolveHelper } from \"@/desktop/install\"\n\n// What happens on THIS machine when a notification is delivered: a banner\n// on screen and a short sound. The push goes to the phone; these are for\n// the person sitting at the Mac that raised the event.\n//\n// Both are awaited rather than fired and forgotten. A caller that exits\n// straight after notifying — a `launchctl submit` job that removes itself,\n// a cron one-liner — used to take the sound down with it before it\n// played. Waiting costs about a second and makes the step reliable.\n//\n// The banner is posted by the AgentX Helper app when it is installed, so\n// it carries the helper's icon (the AgentX logo by default). Without the\n// helper, or before macOS has allowed it to notify, osascript posts it,\n// and macOS shows it as coming from Script Editor.\n//\n// Never fatal: a notification whose banner failed still arrived, and no\n// caller should have to handle an audio error to say a build finished.\n\nexport interface LocalSettings {\n /** Show a desktop banner (macOS only; other platforms skip it). */\n banner: boolean\n /** Play a sound (macOS only). */\n sound: boolean\n /** A macOS system sound, by name: /System/Library/Sounds/<name>.aiff. */\n soundName: string\n /** 0 (silent) … 1 (full). */\n volume: number\n /** Image for the helper's app icon, which macOS puts on its banners.\n * Unset: the AgentX logo. Applied when `agentx desktop install` builds\n * the helper, since macOS reads the icon from the app, not the banner. */\n icon?: string\n}\n\n/** Glass is the gentlest system sound that is still audible over a\n * keyboard — Basso and Sosumi are alerts, Funk and Frog are jokes, and\n * Ping is the one every other app already uses. */\nexport const DEFAULT_LOCAL: LocalSettings = { banner: true, sound: true, soundName: \"Glass\", volume: 0.4 }\n\n/** Shows the banner and plays the sound for one delivered notification. */\nexport type LocalAlert = (title: string, message: string) => Promise<void>\n\n/** Runs a command; resolves true when it exited 0. */\ntype Run = (file: string, args: string[]) => Promise<boolean>\n\n/** Neither step may hold a caller hostage: afplay on a long custom sound,\n * or osascript stuck on a permission prompt, is cut off here. */\nconst STEP_TIMEOUT_MS = 5_000\n\nconst run: Run = (file, args) =>\n new Promise((done) => {\n try {\n execFile(file, args, { timeout: STEP_TIMEOUT_MS }, (err) => done(!err))\n } catch {\n done(false) // no osascript / afplay on this machine — not worth reporting\n }\n })\n\n/** Fill gaps in a partial `notifications.local` block with the defaults. */\nexport function localSettings(cfg: Partial<LocalSettings> | undefined): LocalSettings {\n return { ...DEFAULT_LOCAL, ...(cfg ?? {}) }\n}\n\n/** The system sound file for a name, or null when there is none. Names\n * only — a path in the config must not reach afplay. */\nexport function soundPath(name: string): string | null {\n if (!/^[\\w -]+$/.test(name)) return null\n const path = `/System/Library/Sounds/${name}.aiff`\n return existsSync(path) ? path : null\n}\n\n/** The AgentX Helper binary when one is built or installed, else null.\n * AGENTX_MAC_HELPER points at a helper somewhere else. */\nexport function findHelper(): string | null {\n const path = resolveHelper(packageRoot(), homedir(), process.env.AGENTX_MAC_HELPER)\n return existsSync(path) ? path : null\n}\n\nexport function localAlert(\n settings: LocalSettings,\n deps: { run?: Run; platform?: NodeJS.Platform; helper?: string | null } = {},\n): LocalAlert {\n const exec = deps.run ?? run\n const platform = deps.platform ?? process.platform\n const banner = async (title: string, message: string): Promise<void> => {\n const helper = deps.helper === undefined ? findHelper() : deps.helper\n // A non-zero exit is usually \"not allowed to notify yet\" — the first\n // banner asks — so this one goes through osascript instead.\n if (helper && await exec(helper, [\"notify\", \"--title\", title, \"--message\", message])) return\n // Title and message travel as argv, never spliced into the script,\n // so a quote in either cannot turn into AppleScript.\n await exec(\"/usr/bin/osascript\", [\n \"-e\", \"on run argv\",\n \"-e\", \"display notification (item 2 of argv) with title (item 1 of argv)\",\n \"-e\", \"end run\",\n title, message,\n ])\n }\n return async (title, message) => {\n if (platform !== \"darwin\") return\n const steps: Promise<unknown>[] = []\n if (settings.banner) steps.push(banner(title, message))\n const path = settings.sound ? soundPath(settings.soundName) : null\n if (path) {\n const volume = Math.min(1, Math.max(0, settings.volume))\n steps.push(exec(\"/usr/bin/afplay\", [\"-v\", String(volume), path]))\n }\n await Promise.all(steps)\n }\n}\n\n/**\n * Apply a change to a stored `notifications.local` block, the one rule\n * both the CLI and the dashboard write through. Returns the new block;\n * throws on a value that would not load. Only a Mac has sounds to check a\n * name against — elsewhere the setting is inert, so it need only be\n * well-formed.\n */\nexport function patchLocal(\n current: Partial<LocalSettings> | undefined,\n patch: Record<string, unknown>,\n platform: NodeJS.Platform = process.platform,\n): Partial<LocalSettings> {\n const next = { ...(current ?? {}) }\n if (\"banner\" in patch) next.banner = Boolean(patch.banner)\n if (\"sound\" in patch) next.sound = Boolean(patch.sound)\n if (\"soundName\" in patch) {\n const name = String(patch.soundName).trim()\n const ok = platform === \"darwin\" ? soundPath(name) !== null : /^[\\w -]+$/.test(name)\n if (!ok) throw new Error(`no system sound named \"${name}\" in /System/Library/Sounds`)\n next.soundName = name\n }\n if (\"icon\" in patch) {\n const icon = String(patch.icon ?? \"\").trim().replace(/^~(?=\\/)/, homedir())\n if (!icon) delete next.icon\n else {\n if (!isAbsolute(icon) || !/\\.(png|jpe?g|icns)$/i.test(icon)) throw new Error(\"icon must be the full path to a .png, .jpg or .icns file\")\n if (platform === \"darwin\" && !existsSync(icon)) throw new Error(`no icon file at ${icon}`)\n next.icon = icon\n }\n }\n if (\"volume\" in patch) {\n const v = Number(patch.volume)\n if (!Number.isFinite(v) || v < 0 || v > 1) throw new Error(\"volume must be between 0 and 1\")\n next.volume = v\n }\n return next\n}\n"],"mappings":"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","names":["existsSync","readFileSync","dirname","join","fileURLToPath","DESKTOP_LABEL","DESKTOP_APP","HELPER_APP","desktopPlatformError","platform","arch","release","selectDesktopAgent","agents","requested","id","shellQuote","value","LAUNCHD_PATH","desktopPath","ffmpeg","override","plistPathEnv","plist","m","ents","_","e","findOnPath","bin","path","isExecutable","dir","desktopPlist","opts","xml","s","env","k","v","helperBuildArgs","icon","installedHelper","home","packageRoot","from","resolveHelper","root","installed","execFile","existsSync","homedir","isAbsolute","DEFAULT_LOCAL","STEP_TIMEOUT_MS","run","file","args","done","execFile","err","localSettings","cfg","soundPath","name","path","existsSync","findHelper","resolveHelper","packageRoot","homedir","localAlert","settings","deps","exec","platform","banner","title","message","helper","steps","volume","patchLocal","current","patch","next","icon","isAbsolute","v"]}
|
package/dist/chunk-JUJ3TCOE.js
DELETED
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
import{a as ee}from"./chunk-N6EWZGIX.js";import{b as Fe,c as De}from"./chunk-WP6KLXTP.js";import{b as Oe,c as We,e as je,f as Ee,k as Ce}from"./chunk-JY7POTMB.js";import{b as oe}from"./chunk-AFRHKA7B.js";import{a as xe,b as te,c as ne,d as Ne,e as re}from"./chunk-HRBKSZ34.js";import{v as Te,w as $t}from"./chunk-F2PEUQW4.js";import{b as Pe,f as Rt}from"./chunk-72SZI2UW.js";import{c as Re,d as $e}from"./chunk-QOYAX2FT.js";import{existsSync as Pt,mkdirSync as Me,readFileSync as Tt,writeFileSync as xt,renameSync as Nt}from"fs";import{resolve as _e,dirname as Ot}from"path";var Le=class{filePath;log;constructor(e={}){let t=e.baseDir??_e(process.cwd(),".agentx");this.filePath=_e(t,"handover.json"),this.log=e.log??console.error.bind(console,"[handover]"),Me(t,{recursive:!0})}key(e,t,n){return`${e}::${t}::${n||"-"}`}load(){if(!Pt(this.filePath))return{version:1,overrides:{}};try{let e=Tt(this.filePath,"utf-8"),t=JSON.parse(e);return!t||typeof t!="object"?{version:1,overrides:{}}:(t.overrides||(t.overrides={}),t)}catch(e){return this.log(`load failed, starting empty: ${e?.message||e}`),{version:1,overrides:{}}}}save(e){Me(Ot(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp-${process.pid}`;xt(t,JSON.stringify(e,null,2)),Nt(t,this.filePath)}get(e,t,n){let i=this.load().overrides[this.key(e,t,n)];if(i&&!(i.expiresAt&&Date.parse(i.expiresAt)<Date.now()))return i}set(e){if(!e.channel||!e.chatId||!e.toAgent)throw new Error("channel, chatId and toAgent are required");let t=this.load(),n={...e,createdAt:e.createdAt??new Date().toISOString()};return t.overrides[this.key(n.channel,n.chatId,n.accountId)]=n,this.save(t),n}remove(e,t,n){let o=this.load(),i=this.key(e,t,n);return i in o.overrides?(delete o.overrides[i],this.save(o),!0):!1}consumeSummary(e,t,n){let o=this.load(),i=o.overrides[this.key(e,t,n)];if(!i||!i.summary||i.summaryConsumedAt)return;let s=i.summary;return i.summaryConsumedAt=new Date().toISOString(),this.save(o),s}listActive(){let e=this.load(),t=Date.now();return Object.values(e.overrides).filter(n=>!n.expiresAt||Date.parse(n.expiresAt)>=t)}listByAgent(e){let t=this.listActive();return{incoming:t.filter(n=>n.toAgent===e),outgoing:t.filter(n=>n.fromAgent===e)}}};import{readFileSync as Wt,writeFileSync as ie,appendFileSync as jt,mkdirSync as Et,existsSync as He}from"fs";import{resolve as se}from"path";var Ue=200,Ft=7,Ke=class{memoryDir;constructor(e=process.cwd()){this.memoryDir=se(e,".agentx/memory"),He(this.memoryDir)||Et(this.memoryDir,{recursive:!0})}filePath(e){return se(this.memoryDir,`${e}.jsonl`)}addMemory(e,t){if(t.category==="secret"||te(t.content))return!1;let n=t.source.trust??xe(t.source.channel),o=t.review??Ne(n),i={...t,source:{...t.source,trust:n},...o?{review:o}:{},id:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,createdAt:new Date().toISOString()};return jt(this.filePath(e),JSON.stringify(i)+`
|
|
2
|
-
`),!0}getAll(e){let t=this.filePath(e);if(!He(t))return[];try{return Wt(t,"utf-8").split(`
|
|
3
|
-
`).filter(o=>o.trim()).map(o=>{try{return JSON.parse(o)}catch{return null}}).filter(o=>o!==null)}catch{return[]}}findRelevant(e,t,n=8){let o=this.getAll(t).filter(re);if(o.length===0)return[];let i=o.map(f=>`${f.keywords.join(" ")} ${f.content}`),s=se(this.memoryDir,`${t}_bm25_cache.json`),a=$e(i,s),d=Re(e,a),c=new Map(d.map(f=>[f.docIndex,f.score])),p=o.map((f,h)=>{let m=c.get(h)??0;return f.category==="commitment"&&(m+=1),{memory:f,score:m}}).filter(f=>f.score>0);if(p.length===0)return o.slice(-n);let g=p.sort((f,h)=>h.score-f.score).slice(0,n).map(f=>f.memory);if(g.length>0)try{this.recordAccess(t,g.map(f=>f.id))}catch{}return g}buildContext(e){let t=this.contextLines(e).map(n=>n.line);return t.length===0?"":["[Agent Memory \u2014 persistent facts from past conversations]",...t,"[End Memory]"].join(`
|
|
4
|
-
`)}contextFacts(e){return this.contextLines(e).map(t=>t.fact)}contextLines(e){let t=[],n=57;for(let o of e){let s=!o.source.chatId.startsWith("-")&&/^\d+$/.test(o.source.chatId)?"DM":o.source.chatId,a=`- [${o.category}] ${o.content} (${s}, ${o.source.date})`;if(n+a.length>2400)break;t.push({fact:o,line:a}),n+=a.length}return t}recordAccess(e,t){if(t.length===0)return;let n=this.getAll(e),o=new Set(t),i=!1;for(let s of n)if(o.has(s.id)){s.accessCount=(s.accessCount||0)+1,s.lastAccessed=new Date().toISOString();let a=s.intervalDays||1;s.intervalDays=Math.min(a*2,30),s.nextReview=new Date(Date.now()+s.intervalDays*864e5).toISOString(),i=!0}i&&ie(this.filePath(e),n.map(s=>JSON.stringify(s)).join(`
|
|
5
|
-
`)+`
|
|
6
|
-
`)}getDueForReview(e,t=5){let n=this.getAll(e).filter(re),o=Date.now();return n.filter(i=>i.category==="task-state"?!1:i.nextReview?new Date(i.nextReview).getTime()<=o:!0).sort((i,s)=>!i.nextReview&&s.nextReview?-1:i.nextReview&&!s.nextReview?1:i.nextReview&&s.nextReview?new Date(i.nextReview).getTime()-new Date(s.nextReview).getTime():(i.accessCount||0)-(s.accessCount||0)).slice(0,t)}buildRecallContext(e){let t=this.getDueForReview(e,5);if(t.length===0)return"";let n=["[Memory Recall \u2014 facts due for review, verify they are still accurate]"];for(let o of t){let i=Math.round((Date.now()-new Date(o.createdAt).getTime())/864e5);n.push(`- [${o.category}] ${o.content} (${i}d old, accessed ${o.accessCount||0}x)`)}return n.push("[If any fact is outdated, note the correction. Otherwise, acknowledge recall.]"),n.join(`
|
|
7
|
-
`)}held(e){return this.getAll(e).filter(t=>t.review==="held"||t.review===void 0&&ne(t)==="external")}review(e,t,n,o="operator"){let i=this.getAll(e),s=i.find(a=>a.id===t);return s?(s.review=n,s.reviewedBy=o,s.reviewedAt=new Date().toISOString(),this.rewrite(e,i),!0):!1}scrubSecrets(e,t=!1){let n=this.getAll(e),o=n.filter(s=>s.category!=="secret"&&!te(s.content)),i=n.length-o.length;return t&&i>0&&this.rewrite(e,o),i}trustSummary(e){let t={};for(let n of this.getAll(e)){let o=`${ne(n)}${n.review?`/${n.review}`:""}`;t[o]=(t[o]??0)+1}return t}rewrite(e,t){ie(this.filePath(e),t.map(n=>JSON.stringify(n)).join(`
|
|
8
|
-
`)+(t.length?`
|
|
9
|
-
`:""))}hasSimilar(e,t){let n=this.getAll(e),i=t.toLowerCase().split(/\s+/).filter(s=>s.length>3);return n.some(s=>{let a=s.content.toLowerCase();return i.filter(c=>a.includes(c)).length>=i.length*.7})}prune(e){let t=this.getAll(e);if(t.length===0)return;let n=Date.now(),o=Ft*24*60*60*1e3;t=t.filter(s=>s.category==="task-state"&&s.expiresAt?new Date(s.expiresAt).getTime()>n:s.category==="task-state"&&!s.expiresAt?n-new Date(s.createdAt).getTime()<o:!0),t.length>Ue&&(t=t.slice(-Ue));let i=this.filePath(e);ie(i,t.map(s=>JSON.stringify(s)).join(`
|
|
10
|
-
`)+`
|
|
11
|
-
`)}};import{existsSync as I,mkdirSync as tn,readdirSync as U,readFileSync as K,unlinkSync as B,writeFileSync as ce}from"fs";import{resolve as R,relative as ue}from"path";import{z as u}from"zod";var Dt=u.enum(["trigger.channel","trigger.manual","trigger.cron","trigger.hook","trigger.form","agent","transform","classify","branch","gateway.parallel","rule","action.send","action.createIssue","action.setLabel","action.readLabel","action.react","action.editMessage","action.logTime","action.callHTTP","action.run","action.builtin","subProcess","signal.emit","signal.wait","timer.boundary","checkpoint","end"]),Ct=u.enum(["equals","contains","matches","exists"]),Mt=u.object({kind:Ct,params:u.record(u.unknown()).default({})}),ze=u.object({maxAttempts:u.number().int().min(1).max(10).default(1),backoffMs:u.number().int().min(0).max(6e4).default(1e3)}).default({maxAttempts:1,backoffMs:1e3}),qe=u.object({id:u.string().min(1).regex(/^[a-zA-Z_][a-zA-Z0-9_-]*$/,"node id must be identifier-safe"),type:Dt,config:u.record(u.unknown()).default({}),retry:ze,position:u.object({x:u.number(),y:u.number()}).optional()}),Je=u.object({from:u.string(),fromPort:u.string().optional(),to:u.string(),toPort:u.string().optional(),label:u.string().optional()}),Be=u.union([u.string(),u.date().transform(r=>r.toISOString())]),$=u.object({id:u.string().regex(/^[a-z0-9][a-z0-9_-]*$/,"workflow id must be lower-kebab"),version:u.literal(2).default(2),title:u.string().min(1),description:u.string().optional(),status:u.enum(["draft","review","active","deprecated"]).default("active"),tags:u.array(u.string()).default([]),project:u.string().optional(),entity:u.string().optional(),intentPath:u.array(u.string()).default([]),generatedFrom:u.string().optional(),sourceTaskIds:u.array(u.string()).default([]),confidence:u.number().min(0).max(1).optional(),workflowVersion:u.string().optional(),ownerAgent:u.string().optional(),lastMatchedAt:u.string().optional(),matchCount:u.number().int().min(0).default(0),state:u.enum(["active","disabled","quarantined"]).default("active"),priority:u.number().int().default(0),fanOut:u.boolean().default(!1),nodes:u.array(qe).refine(r=>r.length>0,{message:"workflow must have at least one node"}),edges:u.array(Je).default([]),envAllow:u.array(u.string()).default([]),retention:u.object({maxRuns:u.number().int().positive().default(500),maxDays:u.number().int().positive().default(90)}).default({maxRuns:500,maxDays:90}),maxChildDepth:u.number().int().positive().default(5),mesh:u.object({allowRemote:u.boolean().default(!1),peers:u.array(u.string()).optional()}).default({allowRemote:!1}),created:Be.optional(),updated:Be.optional()});function ae(r){let e=[],t=new Map(r.nodes.map(s=>[s.id,s])),n=r.nodes.filter(s=>s.type.startsWith("trigger."));n.length===0&&e.push("workflow must have exactly one trigger.* node (found 0)"),n.length>1&&e.push(`workflow has ${n.length} trigger.* nodes; v1 supports exactly one`);for(let s of r.edges)t.has(s.from)||e.push(`edge references missing node: from="${s.from}"`),t.has(s.to)||e.push(`edge references missing node: to="${s.to}"`);let o=n[0];if(o){let s=new Map;for(let c of r.edges)s.has(c.from)||s.set(c.from,[]),s.get(c.from).push(c.to);let a=new Set,d=[o.id];for(;d.length;){let c=d.pop();if(!a.has(c)){a.add(c);for(let l of s.get(c)??[])d.push(l)}}for(let c of r.nodes)a.has(c.id)||e.push(`node "${c.id}" is unreachable from trigger "${o.id}"`);r.nodes.some(c=>a.has(c.id)&&_t(c.type))||e.push("no reachable `end`, `checkpoint`, `subProcess`, `signal.wait`, or `timer.boundary` node \u2014 the run cannot terminate or pause")}for(let s of r.nodes){if(s.type!=="branch"&&s.type!=="rule")continue;let a=s.type==="branch"?s.config.cases??[]:(s.config.rules??[]).filter(p=>typeof p.to=="string"),d=s.type==="branch"?s.config.default:s.config.default?.to,c=new Set(a.map(p=>p.to));d&&c.add(d);let l=r.edges.filter(p=>p.from===s.id);for(let p of l){let g=p.fromPort??"";c.has(g)||e.push(`${s.type} "${s.id}" has outgoing edge with port "${g}" not declared in cases or default`)}}let i=Ht(r);for(let s of i)e.push(`cycle without agent/checkpoint: ${s.join(" -> ")}`);return e}function _t(r){return r==="end"||r==="checkpoint"||r==="subProcess"||r==="signal.wait"||r==="timer.boundary"}function Lt(r){return r==="agent"||r==="checkpoint"||r==="subProcess"||r==="signal.wait"||r==="timer.boundary"}function Ht(r){let e=new Map;for(let a of r.edges)e.has(a.from)||e.set(a.from,[]),e.get(a.from).push(a.to);let t=new Map(r.nodes.map(a=>[a.id,a])),n=[],o=new Map,i=[],s=a=>{if(o.get(a)===1){let d=i.indexOf(a);if(d>=0){let c=i.slice(d).concat(a);c.some(p=>{let g=t.get(p)?.type;return g?Lt(g):!1})||n.push(c)}return}if(o.get(a)!==2){o.set(a,1),i.push(a);for(let d of e.get(a)??[])s(d);i.pop(),o.set(a,2)}};for(let a of r.nodes)o.get(a.id)!==2&&s(a.id);return n}var Ye=u.enum(["running","paused","completed","failed","canceled"]),Ut=u.enum(["ok","failed","timeout","skipped","paused","resumed"]),Kt=u.object({at:u.string(),nodeId:u.string(),inputKeys:u.array(u.string()).default([]),status:Ut,output:u.record(u.unknown()).optional(),idempotencyKey:u.string(),note:u.string().optional()}),Bt=u.object({backend:u.string(),id:u.string()}),zt=u.discriminatedUnion("kind",[u.object({kind:u.literal("checkpoint"),nodeId:u.string(),checkpointName:u.string(),resumeMatch:u.record(u.unknown()).default({})}),u.object({kind:u.literal("subProcess"),nodeId:u.string(),childRunId:u.string(),childWorkflowId:u.string()}),u.object({kind:u.literal("signalWait"),nodeId:u.string(),signalName:u.string(),match:u.record(u.unknown()).default({}),scope:u.enum(["workflow","global"]).default("workflow")}),u.object({kind:u.literal("timerWait"),nodeId:u.string(),fireAt:u.string()})]),qt=u.object({id:u.string(),workflowId:u.string(),workflowVersion:u.literal(2),homeNode:u.string(),status:Ye,pausedAt:zt.optional(),context:u.record(u.record(u.unknown())).default({}),pending:u.array(u.string()).default([]),joinCounters:u.record(u.array(u.string())).default({}),entityRef:Bt,history:u.array(Kt).default([]),parentRunId:u.string().nullable().default(null),parentNodeId:u.string().nullable().default(null),rootRunId:u.string().nullable().default(null),depth:u.number().int().min(0).default(0),createdAt:u.string(),updatedAt:u.string()});import Ve from"js-yaml";var Jt=new Set(["branch","gateway.parallel","rule","signal.wait","subProcess","timer.boundary","checkpoint"]),v=class extends Error{constructor(t,n){super(t);this.mark=n;this.name="WorkflowYamlError"}};function L(r,e={}){if(!r||r.trim()==="")throw new v(`${P(e)}empty file \u2014 workflow YAML must contain at least an id, version, title, and one node.`);let t;try{t=Ve.loadAll(r)}catch(o){let i=o?.mark;throw new v(`${P(e)}YAML parse error: ${o?.reason??o?.message??o}`+(i?` (line ${i.line+1}, column ${i.column+1})`:""),i)}if(t.length===0||t.length===1&&t[0]==null)throw new v(`${P(e)}YAML produced no document.`);if(t.length>1)throw new v(`${P(e)}multi-document YAML is not supported in v1; one workflow per file.`);let n=t[0];if(typeof n!="object"||n===null||Array.isArray(n)){let o=Array.isArray(n)?"array":typeof n;throw new v(`${P(e)}top-level YAML must be a mapping (got ${o}).`)}return Ze(n,e)}function Ze(r,e={}){if(!("flow"in r))return r;let t=r.flow;if(t==null){let p={...r};return delete p.flow,p}if(!Array.isArray(t))throw new v(`${P(e)}flow must be an array of node ids (got ${typeof t}).`);for(let p of t)if(typeof p!="string")throw new v(`${P(e)}flow entries must be strings (got ${typeof p}).`);let n=t,o=Array.isArray(r.nodes)?r.nodes:[],i=new Map;for(let p of o)p&&typeof p=="object"&&typeof p.id=="string"&&typeof p.type=="string"&&i.set(p.id,p.type);for(let p of n){if(!i.has(p))throw new v(`${P(e)}flow references unknown node "${p}".`);let g=i.get(p);if(Jt.has(g))throw new v(`${P(e)}flow cannot include ${g} node "${p}"; use explicit edges for ${g} nodes.`)}let s=[];for(let p=0;p<n.length-1;p++)s.push({from:n[p],to:n[p+1]});let a=Array.isArray(r.edges)?r.edges:[],d=new Set,c=[];for(let p of a){if(!p||typeof p!="object")continue;let g=Ge(p.from,p.fromPort,p.to);g&&!d.has(g)?(d.add(g),c.push(p)):g||c.push(p)}for(let p of s){let g=Ge(p.from,void 0,p.to);g&&!d.has(g)&&(d.add(g),c.push(p))}let l={...r,edges:c};return delete l.flow,l}function Ge(r,e,t){return typeof r!="string"||typeof t!="string"?null:`${r}::${typeof e=="string"?e:""}::${t}`}function P(r){return r.filePath?`${r.filePath}: `:""}function Yt(r){return Ve.dump(r,{noRefs:!0,lineWidth:100,sortKeys:!1})}import{Document as Gt,isMap as H,isSeq as Vt,isScalar as Xe,parseDocument as Zt}from"yaml";function Qe(r,e){let t=Zt(r);if(!t.contents||!H(t.contents)){let n=new Gt(e);return t.commentBefore&&(n.commentBefore=t.commentBefore),String(n)}return de(t,t.contents,e),String(t)}function de(r,e,t){let n=Object.keys(t),o=new Set(n),i=new Map;for(let a of e.items){let d=en(a);d!==null&&i.set(d,a)}let s=[];for(let a of n){let d=t[a],c=i.get(a);c?(Xt(r,c,d),s.push(c)):s.push(r.createPair(a,d))}e.items=s}function Xt(r,e,t){let n=e.value;if(t==null){e.value=r.createNode(null);return}if(typeof t!="object"){e.value=r.createNode(t);return}if(Array.isArray(t)){Vt(n)?Qt(r,n,t):e.value=r.createNode(t);return}H(n)?de(r,n,t):e.value=r.createNode(t)}function Qt(r,e,t){if(!(t.length>0&&t.every(s=>s&&typeof s=="object"&&typeof s.id=="string"))){let s=r.createNode(t);e.items=s.items;return}let o=new Map;for(let s of e.items)if(H(s)){let a=s.get("id",!0);Xe(a)&&typeof a.value=="string"&&o.set(a.value,s)}let i=[];for(let s of t){let a=s.id,d=o.get(a);d&&H(d)?(de(r,d,s),i.push(d)):i.push(r.createNode(s))}e.items=i}function en(r){let e=r.key;return Xe(e)&&typeof e.value=="string"?e.value:typeof e=="string"?e:null}var le=class{baseDir;constructor(e={}){this.baseDir=e.baseDir??R(process.cwd(),".agentx/workflows"),tn(this.baseDir,{recursive:!0})}pathFor(e){return this.pathForJson(e)}pathForJson(e){return R(this.baseDir,`${e}.json`)}pathForYaml(e){return R(this.baseDir,`${e}.yaml`)}isWorkflowFile(e){return e.startsWith("_")?!1:e.endsWith(".json")||e.endsWith(".yaml")||e.endsWith(".yml")}idFromFilename(e){return e.replace(/\.(json|ya?ml)$/,"")}readAndParse(e){let t=R(this.baseDir,e),n=K(t,"utf-8");return e.endsWith(".json")?JSON.parse(n):L(n,{filePath:e})}list(){if(!I(this.baseDir))return[];let e=new Map;for(let n of U(this.baseDir,{withFileTypes:!0})){if(!n.isFile()||!this.isWorkflowFile(n.name))continue;let o=this.idFromFilename(n.name),i=e.get(o)??[];i.push(n.name),e.set(o,i)}let t=[];for(let[,n]of e)if(!(n.length>1))try{let o=this.readAndParse(n[0]),i=$.safeParse(o);i.success&&t.push(i.data)}catch{}return t.sort((n,o)=>n.id.localeCompare(o.id))}validateAll(){let e=[];if(!I(this.baseDir))return e;let t=new Map;for(let n of U(this.baseDir,{withFileTypes:!0})){if(!n.isFile()||!this.isWorkflowFile(n.name))continue;let o=this.idFromFilename(n.name),i=t.get(o)??[];i.push(n.name),t.set(o,i)}for(let[n,o]of t){if(o.length>1){let p=[...o].sort();for(let g of p)e.push({id:n,path:ue(this.baseDir,R(this.baseDir,g)),issues:[`duplicate workflow id "${n}" \u2014 found ${p.join(" and ")}; delete one to disambiguate`],isValid:!1});continue}let i=o[0],s=R(this.baseDir,i),a=ue(this.baseDir,s),d;try{d=this.readAndParse(i)}catch(p){let g=p instanceof v?p.message:`parse error: ${p?.message??p}`;e.push({id:n,path:a,issues:[g],isValid:!1});continue}let c=$.safeParse(d);if(!c.success){let p=c.error.issues.map(g=>`${g.path.join(".")||"<root>"}: ${g.message}`);e.push({id:String(d?.id??n),path:a,issues:p,isValid:!1});continue}let l=ae(c.data);e.push({workflow:c.data,issues:l,isValid:l.length===0})}return e}get(e){let t=this.pathForJson(e),n=this.pathForYaml(e),o=R(this.baseDir,`${e}.yml`),i=I(t),s=I(n)||I(o);if(i&&s)return null;if(i)try{let d=JSON.parse(K(t,"utf-8")),c=$.safeParse(d);return c.success?c.data:null}catch{return null}let a=I(n)?n:I(o)?o:null;if(a)try{let d=K(a,"utf-8"),c=L(d,{filePath:ue(this.baseDir,a)}),l=$.safeParse(c);return l.success?l.data:null}catch{return null}if(!I(this.baseDir))return null;for(let d of U(this.baseDir,{withFileTypes:!0}))if(!(!d.isFile()||!this.isWorkflowFile(d.name)||this.idFromFilename(d.name)===e))try{let l=this.readAndParse(d.name),p=$.safeParse(l);if(p.success&&p.data.id===e)return p.data}catch{}return null}save(e,t={}){let n=new Date().toISOString().slice(0,10),o=$.parse({...e,created:e.created||n,updated:n}),i=this.pathForYaml(o.id),s=R(this.baseDir,`${o.id}.yml`),a=I(i)?i:I(s)?s:null;if(!a&&I(this.baseDir)){for(let d of U(this.baseDir,{withFileTypes:!0}))if(!(!d.isFile()||!this.isWorkflowFile(d.name))&&!d.name.endsWith(".json"))try{let c=this.readAndParse(d.name),l=$.safeParse(c);if(l.success&&l.data.id===o.id){a=R(this.baseDir,d.name);break}}catch{}}if(a&&t.convertFromYaml)return B(a),ce(this.pathForJson(o.id),JSON.stringify(o,null,2)+`
|
|
12
|
-
`),o;if(a){let d=K(a,"utf-8");try{let c=Qe(d,o);return ce(a,c),o}catch(c){let l=new Error(`yaml round-trip failed for "${o.id}" at ${a}: ${c?.message??c}`);throw l.yamlPath=a,l}}return ce(this.pathForJson(o.id),JSON.stringify(o,null,2)+`
|
|
13
|
-
`),o}delete(e){let t=this.pathForJson(e),n=this.pathForYaml(e),o=R(this.baseDir,`${e}.yml`),i=!1;return I(t)&&(B(t),i=!0),I(n)&&(B(n),i=!0),I(o)&&(B(o),i=!0),i}};import{createHash as nn,randomUUID as rn}from"crypto";import{appendFileSync as et,existsSync as j,mkdirSync as tt,readdirSync as nt,readFileSync as pe,statSync as rt,unlinkSync as ot,writeFileSync as on}from"fs";import{resolve as W}from"path";function sn(r){return r.replace(/[^a-zA-Z0-9._:#@-]/g,"_").slice(0,200)}function x(r,e,t){return nn("sha1").update(`${r}|${e}|${t}`).digest("hex").slice(0,16)}var fe=class{baseDir;runsDir;indexDir;nodeId;constructor(e){this.baseDir=e.baseDir??W(process.cwd(),".agentx/workflows"),this.runsDir=W(this.baseDir,"_runs"),this.indexDir=W(this.baseDir,"_index"),this.nodeId=e.nodeId,tt(this.runsDir,{recursive:!0}),tt(this.indexDir,{recursive:!0})}runPath(e){return W(this.runsDir,`${e}.jsonl`)}indexPath(e){return W(this.indexDir,`${e.backend}__${sn(e.id)}.json`)}create(e){let t=new Date().toISOString(),n=rn(),o={id:n,workflowId:e.workflowId,workflowVersion:2,homeNode:this.nodeId,status:"running",pausedAt:void 0,context:e.initialContext??{},pending:e.initialPending,entityRef:e.entityRef,history:[],parentRunId:e.parentRunId??null,parentNodeId:e.parentNodeId??null,rootRunId:e.rootRunId??n,depth:e.depth??0,joinCounters:{},createdAt:t,updatedAt:t};return this.appendSnapshot(o),this.writeIndex(e.entityRef,o.id),o}get(e){let t=this.runPath(e);if(!j(t))return null;let n=pe(t,"utf-8").trim();if(!n)return null;let o=null;for(let i of n.split(`
|
|
14
|
-
`)){let s;try{s=JSON.parse(i)}catch{continue}if(s.v===2){if(s.kind==="snapshot")o=s.run;else if(s.kind==="exec"&&o&&o.id===s.runId){let a=o;o={...a,history:[...a.history,s.entry],pending:s.pending,status:s.status??a.status,pausedAt:s.pausedAt===null?void 0:s.pausedAt??a.pausedAt,context:s.context??a.context,joinCounters:s.joinCounters??a.joinCounters,updatedAt:s.entry.at}}}}return o}getActiveByEntity(e){let t=this.indexPath(e);if(!j(t))return null;try{return JSON.parse(pe(t,"utf-8")).runId}catch{return null}}getHomeNodeByEntity(e){let t=this.indexPath(e);if(!j(t))return null;try{return JSON.parse(pe(t,"utf-8")).homeNode}catch{return null}}recordExecution(e){let t=this.get(e.runId);if(!t)return null;if(t.history.some(i=>i.idempotencyKey===e.entry.idempotencyKey))return t;let n={v:2,kind:"exec",runId:e.runId,entry:e.entry,pending:e.nextPending,status:e.status,pausedAt:e.pausedAt===null?null:e.pausedAt,context:e.context,joinCounters:e.joinCounters};et(this.runPath(e.runId),JSON.stringify(n)+`
|
|
15
|
-
`);let o=e.status??t.status;return o==="completed"||o==="failed"||o==="canceled"?this.clearIndex(t.entityRef):this.writeIndex(t.entityRef,t.id),this.get(e.runId)}setStatus(e,t){let n=this.get(e);if(!n)return null;let o={...n,status:t,updatedAt:new Date().toISOString()};return this.appendSnapshot(o),t!=="running"&&t!=="paused"&&this.clearIndex(o.entityRef),o}list(e={}){if(!j(this.runsDir))return[];let t=nt(this.runsDir).filter(o=>o.endsWith(".jsonl")).map(o=>({name:o,mtime:rt(W(this.runsDir,o)).mtimeMs})).sort((o,i)=>i.mtime-o.mtime),n=[];for(let o of t){let i=this.get(o.name.replace(/\.jsonl$/,""));if(i&&!(e.workflowId&&i.workflowId!==e.workflowId)&&(n.push(i),e.limit&&n.length>=e.limit))break}return n}prune(e){if(!j(this.runsDir))return 0;let t=Date.now()-e.maxDays*24*60*60*1e3,n=[];for(let i of nt(this.runsDir)){if(!i.endsWith(".jsonl"))continue;let s=W(this.runsDir,i),a=rt(s).mtimeMs,d=this.get(i.replace(/\.jsonl$/,""));d&&(d.status==="running"||d.status==="paused"||n.push({file:s,run:d,mtime:a}))}n.sort((i,s)=>s.mtime-i.mtime);let o=0;for(let i=0;i<n.length;i++){let s=n[i],a=s.mtime<t,d=i>=e.maxRuns;if(a||d)try{ot(s.file),o++}catch{}}return o}appendSnapshot(e){let t={v:2,kind:"snapshot",run:e};et(this.runPath(e.id),JSON.stringify(t)+`
|
|
16
|
-
`)}writeIndex(e,t){on(this.indexPath(e),JSON.stringify({runId:t,homeNode:this.nodeId,updatedAt:new Date().toISOString()},null,2)+`
|
|
17
|
-
`)}clearIndex(e){let t=this.indexPath(e);if(j(t))try{ot(t)}catch{}}};import{existsSync as it,mkdirSync as an,readFileSync as dn,unlinkSync as cn,writeFileSync as un}from"fs";import{resolve as ge}from"path";import{z as E}from"zod";var st=E.object({version:E.literal(1),nodes:E.record(E.object({x:E.number(),y:E.number()}))}),me=class{baseDir;layoutsDir;constructor(e={}){this.baseDir=e.baseDir??ge(process.cwd(),".agentx/workflows"),this.layoutsDir=ge(this.baseDir,"_layouts"),an(this.layoutsDir,{recursive:!0})}pathFor(e){let t=e.replace(/[^a-zA-Z0-9._-]/g,"_");return ge(this.layoutsDir,`${t}.json`)}get(e){let t=this.pathFor(e);if(!it(t))return null;try{let n=st.safeParse(JSON.parse(dn(t,"utf-8")));return n.success?n.data:null}catch{return null}}save(e,t){let n=st.parse(t);return un(this.pathFor(e),JSON.stringify(n,null,2)+`
|
|
18
|
-
`),n}sync(e,t){let n=this.get(e);if(!n)return null;let o={};for(let s of t)n.nodes[s]&&(o[s]=n.nodes[s]);let i={version:1,nodes:o};return this.save(e,i)}delete(e){let t=this.pathFor(e);return it(t)?(cn(t),!0):!1}};function at(r){return new Set(r.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter(e=>e.length>3))}function ln(r,e){if(r.size===0||e.size===0)return 0;let t=0;for(let n of r)e.has(n)&&t++;return t/Math.max(r.size,e.size)}function pn(r,e){let t=at(r.message),n=e.filter(i=>i.state==="active"&&(i.status??"active")==="active"),o=null;for(let i of n){let s=0,a=[];if(i.ownerAgent&&i.ownerAgent===r.agentId&&(s+=.25,a.push("owner-agent")),r.channel&&i.tags.includes(r.channel)&&(s+=.15,a.push("channel-tag")),r.intentPath?.length&&i.intentPath.length){let p=r.intentPath.filter((g,f)=>i.intentPath[f]===g).length;p>0&&(s+=Math.min(.3,p*.1),a.push("intent-path"))}let d=[i.id,i.title,i.description??"",...i.tags].join(" "),c=ln(t,at(d));c>0&&(s+=Math.min(.35,c),a.push("text-similarity")),(i.matchCount??0)>0&&(s+=Math.min(.1,i.matchCount*.01),a.push("prior-matches"));let l=Math.max(0,Math.min(1,s));(!o||l>o.confidence)&&(o={workflow:i,confidence:l,reasons:a})}return o&&o.confidence>0?o:null}function he(r){let{workflow:e,fromNodeId:t,selectedPort:n}=r,o=e.nodes.find(a=>a.id===t);if(!o)return{nextPending:[]};let i=e.edges.filter(a=>a.from===t);return{nextPending:(o.type==="branch"?i.filter(a=>(a.fromPort??"")===(n??"")):i).map(a=>a.to)}}function we(r,e){let t=r.config.cases??[],n=r.config.default??"";for(let o of t)if(fn(o.when,e))return o.to;return n}function fn(r,e){let t=r.params??{},n=String(t.path??""),o=z(e,n);switch(r.kind){case"equals":return o===t.value;case"contains":return typeof o=="string"?o.includes(String(t.value??"")):Array.isArray(o)?o.some(i=>i===t.value):!1;case"matches":{if(typeof o!="string")return!1;try{return new RegExp(String(t.regex??"")).test(o)}catch{return!1}}case"exists":return o!=null&&o!=="";default:return!1}}function z(r,e){if(!e)return;let t=e.split("."),n=r;for(let o of t){if(n==null||typeof n!="object")return;n=n[o]}return n}function q(r){let e=r.nodes.find(n=>n.type.startsWith("trigger."));if(!e)return null;let t=r.edges.filter(n=>n.from===e.id).map(n=>n.to);return{triggerId:e.id,pending:t}}function N(r,e){return r.nodes.find(t=>t.id===e)}Rt();$t();function gn(r,e,t){let n=r.split(".");if(n[0]==="env"){if(n.length!==2)return"";let i=n[1];if(!t.has(i))return"";let s=process.env[i];return typeof s=="string"?s:""}let o=e;for(let i of n){if(o==null||typeof o!="object")return"";o=o[i]}return o==null?"":typeof o=="object"?JSON.stringify(o):String(o)}function S(r,e,t={}){let n=new Set(t.envAllow||[]);return r.replace(/\{\{\s*([a-zA-Z_][a-zA-Z0-9_.-]*)\s*\}\}/g,(o,i)=>gn(i,e,n))}function b(r,e,t={}){let n={};for(let[o,i]of Object.entries(r))typeof i=="string"?n[o]=S(i,e,t):Array.isArray(i)?n[o]=i.map(s=>typeof s=="string"?S(s,e,t):s):i&&typeof i=="object"?n[o]=b(i,e,t):n[o]=i;return n}var dt="workflow-classify",J="unsure",ct=async r=>{let e=r.node.config,t=r.run.context,n={envAllow:r.workflow.envAllow},o=S(String(e.input??""),t,n).trim();if(!o)return{error:`classify node "${r.node.id}" missing config.input`};let i=e.labels,s=Array.isArray(i)?Object.fromEntries(i.map(m=>[String(m),null])):typeof i=="object"&&i?Object.fromEntries(Object.entries(i).map(([m,y])=>[m,y==null?null:String(y)])):{},a=Object.keys(s);if(a.length<2)return{error:`classify node "${r.node.id}" needs at least two labels`};if(a.includes(J))return{error:`classify node "${r.node.id}": "${J}" is reserved for the low-confidence port`};let d=typeof e.minConfidence=="number"?e.minConfidence:.7,c=e.instructions?S(String(e.instructions),t,n):void 0,l={input:o};if(e.state&&typeof e.state=="object")for(let[m,y]of Object.entries(e.state)){let w=typeof y=="string"?S(y,t,n):y;(w===null||["string","number","boolean"].includes(typeof w))&&(l[m]=w)}let p=await Te(dt,l,{label:Pe(s,c)},{features:{workflow:r.workflow.id,node:r.node.id}});if(!p)return{error:`classify node "${r.node.id}": decision seat unavailable (set decisions.seats.${dt}.mode)`};let g=p.answers.label,f=g.confidence>=d,h=f?g.choice:J;return r.log(`[node:${r.node.id}] classify \u2192 ${g.choice} (${g.confidence.toFixed(2)})${f?"":` \u2014 below ${d}, routing to ${J}`}`),{output:{result:g.choice,label:g.choice,confidence:g.confidence,probabilities:g.probabilities,unsure:!f,port:h},port:h}};var ye=class{active=new Map;waiters=new Map;async acquire(e,t){let n=this.active.get(e)??0;if(n<t){this.active.set(e,n+1);return}return new Promise(o=>{let i=this.waiters.get(e)??[];i.push({resolve:()=>{this.active.set(e,(this.active.get(e)??0)+1),o()}}),this.waiters.set(e,i)})}release(e){let t=this.active.get(e)??0;this.active.set(e,Math.max(0,t-1));let n=this.waiters.get(e);n&&n.length>0&&n.shift().resolve()}stats(e){return{active:this.active.get(e)??0,waiting:this.waiters.get(e)?.length??0}}},Y=new ye;function ut(r,e){return`${r}:${e}`}var F=async r=>({output:r.run.context[r.node.id]??{}}),mn=async r=>{let e=r.node.config,t=String(e.agentId??""),n=String(e.prompt??"");if(!t)return{error:`agent node "${r.node.id}" missing config.agentId`};let o=S(n,r.run.context,{envAllow:r.workflow.envAllow}),i=typeof e.timeoutMinutes=="number"?e.timeoutMinutes:void 0,s=e.autonomy===void 0||e.autonomy===null?void 0:String(e.autonomy);if(s!==void 0&&s!=="report"&&s!=="propose"&&s!=="act")return{error:`agent node "${r.node.id}" has invalid autonomy "${s}" (expected report, propose or act)`};let a=typeof e.maxConcurrent=="number"&&e.maxConcurrent>0?e.maxConcurrent:null,d=a?ut(r.workflow.id,r.node.id):null;if(d&&a){let l=Y.stats(d);l.active>=a&&r.log(`[node:${r.node.id}] gated: ${l.active} active (cap ${a}), ${l.waiting+1} waiting`),await Y.acquire(d,a)}let c=Date.now();try{let l=await r.agents.execute({agentId:t,message:o,workflowRunId:r.run.id,timeoutMinutes:i,...s?{autonomy:s}:{}}),p=Date.now()-c;if(l.error){let h=l.errorKind??"unknown";return r.log(`[node:${r.node.id}] agent "${t}" failed (${h}): ${l.error}`),{error:`[${h}] ${l.error}`}}let f=String(e.resultParser??"acme-result-token")==="json"?_n(l.content):pt(l.content);return{output:{reply:l.content,result:f.result,json:f.json,taskId:l.taskId,durationMs:p,...l.autonomyBlocks?.length?{autonomyBlocks:l.autonomyBlocks}:{}}}}catch(l){return r.log(`[node:${r.node.id}] agent "${t}" threw: ${l.message}`),{error:l.message}}finally{d&&Y.release(d)}},hn=async r=>{let e=we(r.node,r.run.context);return e?{output:{port:e},port:e}:(r.log(`[node:${r.node.id}] branch matched no case and no default port`),{output:{port:null}})},wn=async r=>{let e=b(r.node.config,r.run.context,{envAllow:r.workflow.envAllow}),t=String(e.channel??""),n=String(e.chatId??""),o=String(e.text??"");if(!t||!n){let a=String(r.node.config.chatId??""),d=String(r.node.config.channel??""),c=[];return t||c.push(`channel config="${d}" rendered=""`),n||c.push(`chatId config="${a}" rendered=""`),(/\{\{\s*env\./.test(a)||/\{\{\s*env\./.test(d))&&c.push("(env.* templates only resolve for names listed in workflow.envAllow and actually set in process.env)"),{error:`action.send "${r.node.id}" needs channel + chatId \u2014 ${c.join("; ")}`}}let i=be(r,e.accountId),s=r.channels[t];if(s?.send)try{return{output:{messageId:await s.send({channel:t,chatId:n,text:o,...i?{accountId:i}:{}})??null}}}catch(a){return{error:`action.send failed: ${a.message}`}}if(r.forwardChannelSend)try{return{output:{messageId:(await r.forwardChannelSend({channel:t,chatId:n,text:o,accountId:i})).messageId,viaMesh:!0}}}catch(a){return r.log(`[node:${r.node.id}] mesh-forward of "${t}" send failed: ${a.message}`),{error:`action.send via mesh failed: ${a.message}`}}return r.log(`[node:${r.node.id}] adapter "${t}" not available locally and no mesh forwarder`),{error:`channel "${t}" not available (no local adapter, no mesh route)`}},yn=async r=>{let e=b(r.node.config,r.run.context,{envAllow:r.workflow.envAllow}),t=String(e.channel??"gitlab"),n=String(e.project??""),o=String(e.title??""),i=String(e.description??""),s=Array.isArray(e.labels)?e.labels.map(String):[],a=Array.isArray(e.assignees)?e.assignees.map(String):[];if(!n||!o)return{error:`action.createIssue "${r.node.id}" needs project + title`};let d=ve(r),c=r.channels[t];if(!c?.createIssue)return{error:`channel "${t}" does not support createIssue`};try{let l=await c.createIssue({project:n,title:o,description:i,labels:s,assignees:a,agentId:d});return l?{output:{issue:{iid:l.iid,url:l.url,webUrl:l.url}}}:{error:"createIssue returned null (see adapter log)"}}catch(l){return{error:`action.createIssue failed: ${l.message}`}}},kn=async()=>({output:{}}),bn=async r=>{let e=r.node.config,t=String(e.name??r.node.id),n=e.waitFor??{},o=e.resumeMatch??{};return{paused:!0,pausedAt:{kind:"checkpoint",nodeId:r.node.id,checkpointName:t,resumeMatch:{...n,...o}}}},vn=async r=>{let e=b(r.node.config,r.run.context,{envAllow:r.workflow.envAllow}),t=String(e.channel??"gitlab"),n=String(e.project??""),o=String(e.iid??""),i=Array.isArray(e.add)?e.add.map(String):[],s=Array.isArray(e.remove)?e.remove.map(String):[];if(!n||!o)return{error:`action.setLabel "${r.node.id}" needs project + iid (try {{trigger.project}} / {{trigger.issue.iid}})`};if(i.length===0&&s.length===0)return{output:{skipped:!0,reason:"no labels to add or remove"}};let a=r.channels[t];if(!a?.setLabels)return{error:`channel "${t}" does not support setLabels`};let d=ve(r),c=e.kind==="merge_request"?"merge_request":"issue";return{output:{labels:await a.setLabels({project:n,kind:c,iid:o,add:i,remove:s,agentId:d})??[],add:i,remove:s}}},In=async r=>{let e=b(r.node.config,r.run.context,{envAllow:r.workflow.envAllow}),t=String(e.channel??"gitlab"),n=String(e.project??""),o=String(e.iid??"");if(!n||!o)return{error:`action.readLabel "${r.node.id}" needs project + iid`};let i=r.channels[t];if(!i?.getLabels)return{error:`channel "${t}" does not support getLabels`};let s=e.kind==="merge_request"?"merge_request":"issue";return{output:{labels:await i.getLabels({project:n,kind:s,iid:o})??[]}}},Sn=async r=>{let e=b(r.node.config,r.run.context,{envAllow:r.workflow.envAllow}),t=String(e.channel??""),n=String(e.chatId??""),o=String(e.messageId??""),i=String(e.emoji??"\u{1F440}");if(!t||!n||!o)return{error:`action.react "${r.node.id}" needs channel + chatId + messageId`};let s=be(r,e.accountId),a=r.channels[t];if(!a?.react)return{error:`channel "${t}" does not support react`};try{return await a.react(n,o,i,s),{output:{emoji:i}}}catch(d){return{error:`action.react failed: ${d.message}`}}},An=async r=>{let e=b(r.node.config,r.run.context,{envAllow:r.workflow.envAllow}),t=String(e.channel??""),n=String(e.chatId??""),o=String(e.messageId??""),i=String(e.text??""),s=e.parseMode?String(e.parseMode):void 0;if(!t||!n||!o||!i)return{error:`action.editMessage "${r.node.id}" needs channel + chatId + messageId + text`};let a=be(r,e.accountId),d=r.channels[t];if(!d?.editMessage)return{error:`channel "${t}" does not support editMessage`};try{return{output:{edited:await d.editMessage(n,o,i,s,a)}}}catch(c){return{error:`action.editMessage failed: ${c.message}`}}},Rn=async r=>{let e=b(r.node.config,r.run.context,{envAllow:r.workflow.envAllow}),t=String(e.channel??"gitlab"),n=String(e.chatId??""),o=Number(e.durationMs??0);if(!n||!o)return{error:`action.logTime "${r.node.id}" needs chatId + durationMs`};let i=r.channels[t];if(!i?.logTimeSpent)return{error:`channel "${t}" does not support logTimeSpent`};let s=ve(r);try{return await i.logTimeSpent(n,o,s),{output:{durationMs:o}}}catch(a){return{error:`action.logTime failed: ${a.message}`}}},$n=async r=>{let e=b(r.node.config,r.run.context,{envAllow:r.workflow.envAllow}),t=String(e.url??"");if(!t)return{error:`action.callHTTP "${r.node.id}" needs url`};let n=String(e.method??"POST").toUpperCase(),o=e.headers&&typeof e.headers=="object"?e.headers:{"Content-Type":"application/json"},i;e.body!==void 0&&(i=typeof e.body=="string"?e.body:JSON.stringify(e.body));try{let s=await fetch(t,{method:n,headers:o,body:i}),a=await s.text(),d=a;try{d=JSON.parse(a)}catch{}return{output:{ok:s.ok,status:s.status,body:d}}}catch(s){return{error:`action.callHTTP failed: ${s.message}`}}},Pn=async r=>{let e=b(r.node.config,r.run.context,{envAllow:r.workflow.envAllow}),t=String(e.actionId??e.id??"");if(!t)return{error:`action.run "${r.node.id}" needs actionId`};let n=e.inputs&&typeof e.inputs=="object"?e.inputs:{},{ActionStore:o}=await import("./store-TWQPEM5V.js"),{runAction:i}=await import("./runner-56G3N7M4.js"),s=new o().get(t);if(!s)return{error:`action.run "${r.node.id}": no action "${t}" in registry`};try{let a=await i(s,n),d={ok:a.ok,output:a.output,status:a.status,durationMs:a.durationMs};return a.errors!==void 0&&(d.errors=a.errors),a.ok?{output:d}:{output:d,error:`action "${t}" failed (status=${a.status})`}}catch(a){return{error:`action.run failed: ${a.message}`}}},Tn=async r=>{let e=b(r.node.config,r.run.context,{envAllow:r.workflow.envAllow}),t=String(e.name??"");if(!t)return{error:`action.builtin "${r.node.id}" needs a "name" (e.g. "http.fetch")`};let n=e.input&&typeof e.input=="object"?e.input:{},{runBuiltin:o,getBuiltin:i}=await import("./builtin-W6KNX7RS.js");if(!i(t))return{error:`action.builtin "${r.node.id}": unknown built-in "${t}"`};try{return{output:await o(t,n)}}catch(s){let a=s?.name==="ZodError"?`validation: ${s.message}`:s?.message||String(s);return{error:`action.builtin "${t}" failed: ${a}`}}},xn=async r=>{let e=r.node.config,t=r.run.context;return typeof e.path=="string"&&e.path?{output:{value:z(t,e.path)}}:e.template&&typeof e.template=="object"?{output:b(e.template,t,{envAllow:r.workflow.envAllow})}:{output:{}}};function Nn(r){if(r!=null){if(typeof r=="number")return new Date(Date.now()+r*6e4).toISOString();if(typeof r=="object"&&r&&"minutes"in r){let e=Number(r.minutes);if(Number.isFinite(e))return new Date(Date.now()+e*6e4).toISOString()}if(typeof r=="string"){let e=/^P(?:([0-9]+)D)?(?:T(?:([0-9]+)H)?(?:([0-9]+)M)?(?:([0-9]+)S)?)?$/.exec(r);if(e){let t=Number(e[1]??0),n=Number(e[2]??0),o=Number(e[3]??0),i=Number(e[4]??0),s=((t*24+n)*60+o)*6e4+i*1e3;if(s>0)return new Date(Date.now()+s).toISOString()}}}}var On=async r=>{let e=r.node.config,t=b(e,r.run.context,{envAllow:r.workflow.envAllow}),n=String(t.workflowId??"");if(!n)return{error:`subProcess "${r.node.id}" missing config.workflowId`};let o=r.run.depth??0,i=r.workflow.maxChildDepth??5;if(o+1>=i)return{error:`max child workflow depth ${i} exceeded at ${r.workflow.id} \u2192 ${n} (parent depth ${o})`};let s=e.inputMap,a={};if(s==="*")a={...r.run.context};else if(s&&typeof s=="object")for(let[d,c]of Object.entries(s))c&&typeof c=="object"&&!Array.isArray(c)?a[d]=b(c,r.run.context,{envAllow:r.workflow.envAllow}):typeof c=="string"&&(a[d]={value:S(c,r.run.context,{envAllow:r.workflow.envAllow})});return{paused:!0,pausedAt:{kind:"subProcess",nodeId:r.node.id,childRunId:"",childWorkflowId:n},spawnChild:{workflowId:n,input:a}}},Wn=F,jn=async r=>{let e=r.node.config,t=b(e,r.run.context,{envAllow:r.workflow.envAllow}),n=String(t.name??"");if(!n)return{error:`signal.emit "${r.node.id}" missing config.name`};let o=t.scope==="global"?"global":"workflow",i=t.payload&&typeof t.payload=="object"?t.payload:{};return{output:{emittedAt:new Date().toISOString(),name:n,scope:o,payload:i},emitSignal:{name:n,scope:o,payload:i}}},En=async r=>{let e=r.node.config,t=b(e,r.run.context,{envAllow:r.workflow.envAllow}),n=String(t.name??"");if(!n)return{error:`signal.wait "${r.node.id}" missing config.name`};let o=t.scope==="global"?"global":"workflow",i=e.match&&typeof e.match=="object"?e.match:{};return{paused:!0,pausedAt:{kind:"signalWait",nodeId:r.node.id,signalName:n,match:i,scope:o}}},Fn=async r=>{let e=r.node.config,t=b(e,r.run.context,{envAllow:r.workflow.envAllow}),n=Nn(t.after??e.after);return n?{paused:!0,pausedAt:{kind:"timerWait",nodeId:r.node.id,fireAt:n}}:{error:`timer.boundary "${r.node.id}" needs config.after (duration or minutes)`}},Dn=async()=>({output:{}}),Cn=async r=>{let e=r.node.config,n=(Array.isArray(e.inputs)?e.inputs:[]).map(s=>typeof s=="string"?S(s,r.run.context,{envAllow:r.workflow.envAllow}):s),o=Array.isArray(e.rules)?e.rules:[];for(let s of o){let a=Array.isArray(s.when)?s.when:[];if(a.length!==n.length)continue;let d=!0;for(let c=0;c<a.length;c++)if(!Mn(a[c],n[c])){d=!1;break}if(d)return{output:{...s.output??{},matchedPort:s.to??""},port:s.to}}let i=e.default;return{output:{...i?.output??{},matchedPort:i?.to??""},port:i?.to}};function Mn(r,e){if(r==null||r==="*")return!0;let t=String(r),n=typeof e=="number"?e:String(e??""),o=/^(>=|<=|>|<)\s*(-?\d+(?:\.\d+)?)$/.exec(t);if(o){let i=o[1],s=Number(o[2]),a=typeof n=="number"?n:Number(n);if(Number.isNaN(a))return!1;switch(i){case">":return a>s;case"<":return a<s;case">=":return a>=s;case"<=":return a<=s}}if(t.startsWith("!="))return String(n)!==t.slice(2);if(t.startsWith("/")&&t.endsWith("/")&&t.length>2)try{return new RegExp(t.slice(1,-1)).test(String(n))}catch{return!1}return String(n)===t}var lt={"trigger.channel":F,"trigger.manual":F,"trigger.cron":F,"trigger.hook":F,"trigger.form":Wn,agent:mn,classify:ct,branch:hn,transform:xn,"gateway.parallel":Dn,rule:Cn,"action.send":wn,"action.createIssue":yn,"action.setLabel":vn,"action.readLabel":In,"action.react":Sn,"action.editMessage":An,"action.logTime":Rn,"action.callHTTP":$n,"action.run":Pn,"action.builtin":Tn,subProcess:On,"signal.emit":jn,"signal.wait":En,"timer.boundary":Fn,checkpoint:bn,end:kn};function ke(r){return lt[r]}function be(r,e){if(typeof e=="string"&&e)return e;let t=r.workflow.nodes.find(i=>i.type.startsWith("trigger."));if(!t)return;let o=r.run.context[t.id]?.accountId;return typeof o=="string"&&o?o:void 0}function ve(r){for(let e=r.run.history.length-1;e>=0;e--){let t=r.run.history[e],n=r.workflow.nodes.find(o=>o.id===t.nodeId);if(n?.type==="agent")return n.config.agentId??void 0}}function pt(r){if(!r)return{};let e=r.match(/\bRESULT:\s*([a-z][a-z0-9_-]*)/i);if(e)return{result:e[1].toLowerCase()};let t=r.match(/\[(APPROVED|REJECTED|CHANGES[-_]REQUESTED|DONE|FAILED|SKIPPED)\]/i);return t?{result:t[1].toLowerCase().replace("_","-")}:{}}function _n(r){let{result:e}=pt(r);if(!r)return{result:e};let t=r.match(/```(?:json)?\s*([\s\S]*?)```/);if(!t)return{result:e};try{return{result:e,json:JSON.parse(t[1])}}catch{return{result:e}}}var D=class{handlers=new Set;subscribe(e){return this.handlers.add(e),()=>this.handlers.delete(e)}emit(e){for(let t of this.handlers)try{Promise.resolve(t(e)).catch(()=>{})}catch{}}};function G(r,e){if(r.name!==e.name||r.scope==="workflow"&&r.workflowId!==e.workflowId)return!1;for(let[t,n]of Object.entries(r.match??{}))if(!(n===void 0||n===""||n==="*")&&e.payload[t]!==n)return!1;return!0}function Ln(r,e,t=Date.now){return{ts:t(),source:"workflow",sourceEventId:`${r.workflowId}:${r.eventId}`,project:r.project,subject:`workflow:${r.workflowId}:entity:${r.entityRef.backend}:${r.entityRef.id}`,intent:`workflow.${r.triggerSource}`,rawJson:e}}function Hn(r){return r.claimed&&r.runId?{agentId:`workflow-run:${r.runId}`,outcome:"dispatched",reason:r.reason??"claimed"}:r.claimed&&!r.runId?{agentId:null,outcome:"halted",reason:r.reason??"claimed-but-no-run"}:{agentId:null,outcome:"halted",reason:r.reason??"not-claimed"}}function Un(r){return{decidedBy:"workflow-dispatcher",decide:()=>({agentId:r.agentId,outcome:r.outcome==="deduped"?"halted":r.outcome,reason:r.outcome==="deduped"?`legacy-dedup: ${r.reason??""}`.trim():r.reason??null})}}function ft(r,e,t,n,o=Date.now){let i=Ln(e,t,o),s=Hn(n),a=Un(s),d=je(r,i,a,o);return Ee(r,"workflow",d,s,o),d}var Kn=4e3,Bn=8,Ie=class{store;runs;nodeId;forwarder;channels;agents;log;timers;signals;events;ackTypingTimers=new Map;commitChains=new Map;constructor(e){this.store=e.store,this.runs=e.runs,this.nodeId=e.nodeId,this.forwarder=e.forwarder,this.channels=e.channels,this.agents=e.agents,this.log=e.log??(()=>{}),this.timers=e.timers??new oe({log:t=>this.log(t)}),this.signals=e.signals??new D,this.events=e.events,this.timers.onFire(t=>this.resumeFromTimer(t)),this.signals.subscribe(t=>this.resumeFromSignal(t))}emitRunEvent(e){if(this.events)try{this.events.publish({kind:"run",runId:e.runId,workflowId:e.workflowId,nodeId:e.nodeId,phase:e.phase,status:e.status,note:e.note,homeNode:e.homeNode})}catch{}}async commit(e,t){let o=(this.commitChains.get(e)??Promise.resolve()).then(()=>t(),()=>t());return this.commitChains.set(e,o.then(()=>{},()=>{})),o}emitSignal(e){let t={name:e.name,scope:e.scope??"global",workflowId:e.workflowId??"",payload:e.payload??{},emittedAt:new Date().toISOString()};if(this.signals.emit(t),this.events)try{this.events.publish({kind:"signal",name:t.name,scope:t.scope,workflowId:t.workflowId||void 0,payload:t.payload})}catch{}return t}async resumeFromSignal(e){let t=this.runs.list({limit:500});for(let n of t){if(n.status!=="paused"||!n.pausedAt||n.pausedAt.kind!=="signalWait")continue;let o={name:n.pausedAt.signalName,scope:n.pausedAt.scope,workflowId:n.workflowId,match:n.pausedAt.match??{}};if(!G(o,e))continue;let i=this.store.list().find(s=>s.id===n.workflowId);i&&(await this.commit(n.id,()=>{let s=this.runs.get(n.id);if(!s||s.status!=="paused"||!s.pausedAt||s.pausedAt.kind!=="signalWait"||!G({name:s.pausedAt.signalName,scope:s.pausedAt.scope,workflowId:s.workflowId,match:s.pausedAt.match??{}},e))return;let a=N(i,s.pausedAt.nodeId),d=a?i.edges.filter(l=>l.from===a.id).map(l=>l.to):[],c={receivedAt:new Date().toISOString(),name:e.name,payload:e.payload};this.runs.recordExecution({runId:s.id,entry:{at:c.receivedAt,nodeId:s.pausedAt.nodeId,inputKeys:[],status:"resumed",output:c,idempotencyKey:x(s.id,s.pausedAt.nodeId,`signal:${e.name}:${e.emittedAt}`)},nextPending:d,status:"running",pausedAt:null,context:{...s.context,[s.pausedAt.nodeId]:c}}),this.log(`[workflow:${i.id}] run ${s.id} resumed from signal "${e.name}"`),this.emitRunEvent({runId:s.id,workflowId:i.id,nodeId:s.pausedAt.nodeId,phase:"resumed",status:"running",note:`signal:${e.name}`})}),this.walk(i,n.id,`signal:${e.name}`).catch(s=>this.log(`[workflow:${i.id}] walk-after-signal failed: ${s.message}`)))}}async resumeFromTimer(e){let t=this.store.list().find(n=>n.id===(this.runs.get(e.runId)?.workflowId??""));t&&(await this.commit(e.runId,()=>{let n=this.runs.get(e.runId);if(!n||n.status!=="paused"||!n.pausedAt||n.pausedAt.kind!=="timerWait"||n.pausedAt.nodeId!==e.nodeId)return;let o=N(t,e.nodeId),i=o?t.edges.filter(d=>d.from===o.id).map(d=>d.to):[],s=new Date().toISOString(),a={firedAt:s,scheduledFor:e.fireAt};this.runs.recordExecution({runId:n.id,entry:{at:s,nodeId:e.nodeId,inputKeys:[],status:"resumed",output:a,idempotencyKey:x(n.id,e.nodeId,`timer:${e.id}`)},nextPending:i,status:"running",pausedAt:null,context:{...n.context,[e.nodeId]:a}}),this.log(`[workflow:${t.id}] run ${n.id} resumed from timer "${e.nodeId}" (fired ${s})`),this.emitRunEvent({runId:n.id,workflowId:t.id,nodeId:e.nodeId,phase:"resumed",status:"running",note:`timer:${e.id}`})}),this.walk(t,e.runId,`timer:${e.id}`).catch(n=>this.log(`[workflow:${t.id}] walk-after-timer failed: ${n.message}`)))}async dispatchWorkflow(e){let t=this.store.list().find(s=>s.id===e.workflowId);if(!t)return this.log(`[workflows] dispatchWorkflow: workflow "${e.workflowId}" not found`),{claimed:!1,run:null};let o=t.nodes.find(s=>s.type.startsWith("trigger."))?.config??{},i={source:e.trigger?.source??o.source??"hook",project:e.trigger?.project,repo:e.trigger?.repo,chat:e.trigger?.chat,labels:e.trigger?.labels};return this.dispatchOne(t,e.entityRef,e.event,i)}startChannelAck(e,t){let n=String(t.channel??""),o=String(t.chatId??"");if(!n||!o)return;let i=this.channels[n];if(!i)return;let s=typeof t.accountId=="string"?t.accountId:void 0,a=t.event,d=typeof a?.id=="string"?a.id:a?.id!=null?String(a.id):void 0;if(d&&i.react)try{Promise.resolve(i.react(o,d,"\u{1F440}",s)).catch(()=>{})}catch{}if(this.ackTypingTimers.has(e)||!i.sendTyping)return;let c=()=>{try{Promise.resolve(i.sendTyping(o,s)).catch(()=>{})}catch{}};c();let l=setInterval(c,Kn);this.ackTypingTimers.set(e,l)}stopChannelAck(e){let t=this.ackTypingTimers.get(e);t&&(clearInterval(t),this.ackTypingTimers.delete(e))}async dispatch(e){let t=this.matchByTrigger(e.trigger,e.fromRemote),o=t.some(a=>a.fanOut)?t:t.slice(0,1),i=[],s=[];for(let a of o){let d=await this.dispatchOne(a,e.entityRef,e.event,e.trigger);d.claimed&&i.push(a),d.run&&s.push(d.run)}return!e.fromRemote&&this.forwarder?.broadcastTrigger&&Promise.resolve(this.forwarder.broadcastTrigger({trigger:e.trigger,entityRef:e.entityRef,event:e.event})).catch(a=>this.log(`[mesh-broadcast] ${a?.message??a}`)),{claimed:i,runs:s}}matchByTrigger(e,t){let n=this.store.list(),o=[];for(let i of n){if(i.state&&i.state!=="active")continue;if(t){if(!i.mesh?.allowRemote)continue;let c=i.mesh.peers;if(c&&c.length>0&&!c.includes(t.peer))continue}let s=i.nodes.find(c=>c.type.startsWith("trigger."));if(!s)continue;let a=s.config;if(a.source!==e.source||i.project&&e.project&&i.project!==e.project)continue;let d=a.filter;if(d){if(d.project&&d.project!=="*"&&d.project!==e.project||d.repo&&d.repo!=="*"&&d.repo!==e.repo||d.chat&&d.chat!=="*"&&V(e.source,d.chat)!==V(e.source,e.chat))continue;if(d.labels?.length){let c=new Set(e.labels??[]);if(!d.labels.some(p=>c.has(p)))continue}}o.push(i)}return o.sort((i,s)=>s.priority-i.priority||i.id.localeCompare(s.id))}async dispatchOne(e,t,n,o){let i=await this.dispatchOneLegacy(e,t,n,o);if(We("workflow")!=="off")try{ft(Oe(),{workflowId:e.id,eventId:n.id,triggerSource:o.source,project:o.project??null,entityRef:t},JSON.stringify({event:n,trigger:o,entityRef:t}),{claimed:i.claimed,runId:i.run?.id??null})}catch(s){this.log(`[ledger] workflow ${e.id} run ${i.run?.id??"?"} record failed: ${s?.message??s}`)}return i}async dispatchOneLegacy(e,t,n,o){let i=this.runs.getActiveByEntity(t),s=i?this.runs.getHomeNodeByEntity(t):null;if(i&&s&&s!==this.nodeId){if(!this.forwarder)return this.log(`[workflow:${e.id}] run ${i} home'd on "${s}" but no forwarder \u2014 dropping`),{claimed:!1,run:null};try{await this.forwarder.forwardTransition(s,{workflowId:e.id,event:n,entityRef:t})}catch(d){this.log(`[workflow:${e.id}] forward to "${s}" failed: ${d.message}`)}return{claimed:!0,run:null}}let a=i?this.runs.get(i):null;if(a)if(a.status==="paused"&&a.pausedAt){if(a.pausedAt.kind!=="checkpoint")return this.log(`[workflow:${e.id}] run ${a.id} paused on ${a.pausedAt.kind} \u2014 channel event bypasses workflow`),{claimed:!1,run:null};if(!qn(a.pausedAt.resumeMatch,o,n))return this.log(`[workflow:${e.id}] run ${a.id} paused but event doesn't match resumeMatch \u2014 dropping`),{claimed:!1,run:null};let d=N(e,a.pausedAt.nodeId),c=d?e.edges.filter(h=>h.from===d.id).map(h=>h.to):[],l={at:new Date().toISOString(),nodeId:a.pausedAt.nodeId,inputKeys:[],status:"resumed",output:{event:n.payload},idempotencyKey:x(a.id,a.pausedAt.nodeId,`resume:${n.id}`)},p={...a.context,[a.pausedAt.nodeId]:{event:n.payload}},g=a.pausedAt.checkpointName,f=this.runs.recordExecution({runId:a.id,entry:l,nextPending:c,status:"running",pausedAt:null,context:p});f&&(a=f),this.log(`[workflow:${e.id}] run ${a.id} resumed from checkpoint "${g}"`),o.source.endsWith("-message")&&this.startChannelAck(a.id,n.payload)}else return a.status==="running"?(this.log(`[workflow:${e.id}] run ${a.id} already running; dropping concurrent event ${n.id}`),{claimed:!0,run:null}):(this.log(`[workflow:${e.id}] run ${a.id} is ${a.status}; dropping event ${n.id}`),{claimed:!1,run:null});else{let d=q(e);if(!d)return this.log(`[workflow:${e.id}] no trigger node found`),{claimed:!1,run:null};a=this.runs.create({workflowId:e.id,initialPending:d.pending,entityRef:t,initialContext:{[d.triggerId]:n.payload}}),this.log(`[workflow:${e.id}] run ${a.id} created from trigger "${d.triggerId}" for ${t.id}`),this.emitRunEvent({runId:a.id,workflowId:e.id,phase:"created",status:a.status,homeNode:a.homeNode}),o.source.endsWith("-message")&&this.startChannelAck(a.id,n.payload)}return this.walk(e,a.id,n.id),{claimed:!0,run:a}}async walk(e,t,n){try{await this.walkInner(e,t,n)}finally{this.stopChannelAck(t)}}async walkInner(e,t,n){let o=this.runs.get(t);if(o)for(;o.status==="running"&&o.pending.length>0;){let i=o.pending.slice(0,Bn);await Promise.allSettled(i.map(a=>this.executeNodeAndCommit(e,t,a,n)));let s=this.runs.get(t);if(!s||(o=s,o.status!=="running"))return}}async executeNodeAndCommit(e,t,n,o){let i=x(t,n,o),s=await this.commit(t,()=>{let m=this.runs.get(t);if(!m)return{kind:"done"};if(m.status!=="running")return{kind:"done"};let y=N(e,n);if(!y)return this.log(`[workflow:${e.id}] missing node "${n}" \u2014 marking run failed`),this.runs.recordExecution({runId:t,entry:{at:new Date().toISOString(),nodeId:n,inputKeys:[],status:"failed",idempotencyKey:i,note:"node definition missing from workflow"},nextPending:m.pending.filter(A=>A!==n),status:"failed"}),{kind:"done"};let w=ke(y.type);return w?m.history.some(A=>A.idempotencyKey===i)?(this.runs.recordExecution({runId:t,entry:{at:new Date().toISOString(),nodeId:n,inputKeys:[],status:"skipped",idempotencyKey:i+"_dedup",note:"duplicate execution dropped"},nextPending:m.pending.filter(A=>A!==n)}),{kind:"done"}):{kind:"go",run:m,node:y,handler:w}:(this.log(`[workflow:${e.id}] no handler for node type "${y.type}"`),this.runs.recordExecution({runId:t,entry:{at:new Date().toISOString(),nodeId:n,inputKeys:[],status:"failed",idempotencyKey:i,note:`no handler for node type "${y.type}"`},nextPending:m.pending.filter(A=>A!==n),status:"failed"}),{kind:"done"})});if(s.kind==="done")return;let{run:a,node:d,handler:c}=s,l=e.edges.filter(m=>m.to===n).map(m=>m.from),p;if(d.type!=="agent"){let m=ee();if(m)try{p=Fe(m,{agentId:`workflow:${d.type}`,channel:"workflow",chatId:`${e.id}:${n}`,workflowRunId:t,workflowId:e.id,workflowNodeId:n,messagePreview:`${d.type} ${n}`})}catch{}}let g=d.retry??{maxAttempts:1,backoffMs:1e3},f={error:"retry-loop did not run"},h=0;for(;h<g.maxAttempts;){h++;try{f=await c({workflow:e,run:a,node:d,channels:this.channels,agents:this.agents,forwardChannelSend:this.forwarder?.forwardChannelSend?.bind(this.forwarder),log:this.log})}catch(m){this.log(`[workflow:${e.id}] handler "${d.type}" threw: ${m.message}`),f={error:m.message}}if(!f.error||f.paused)break;if(h<g.maxAttempts){let m=g.backoffMs*Math.pow(2,h-1);this.log(`[workflow:${e.id}] node "${n}" failed (attempt ${h}/${g.maxAttempts}): ${f.error.slice(0,120)} \u2014 retrying in ${m}ms`),await new Promise(y=>setTimeout(y,m))}}if(p){let m=ee();if(m)try{De(m,p,{status:f.error?"error":"ok",error:f.error??null})}catch{}}await this.commit(t,async()=>{let m=this.runs.get(t);if(!m)return;let y=new Date().toISOString(),w=m.pending.filter(k=>k!==n);if(f.error){let k=m.status==="running"?"failed":void 0;this.runs.recordExecution({runId:t,entry:{at:y,nodeId:n,inputKeys:l,status:"failed",idempotencyKey:i,note:f.error.slice(0,200)},nextPending:w,status:k}),this.emitRunEvent({runId:t,workflowId:e.id,nodeId:n,phase:"failed",status:k??m.status,note:f.error.slice(0,200)});return}if(f.paused&&f.pausedAt){let k=f.pausedAt,T=null;if(f.spawnChild&&k.kind==="subProcess"){if(T=await this.spawnChild({parent:m,parentNodeId:n,childWorkflowId:f.spawnChild.workflowId,input:f.spawnChild.input}),!T){this.runs.recordExecution({runId:t,entry:{at:y,nodeId:n,inputKeys:l,status:"failed",idempotencyKey:i,note:`subProcess: child workflow "${f.spawnChild.workflowId}" not found`},nextPending:w,status:"failed"});return}k={...k,childRunId:T.id}}if(this.runs.recordExecution({runId:t,entry:{at:y,nodeId:n,inputKeys:l,status:"paused",idempotencyKey:i},nextPending:w,status:"paused",pausedAt:k}),this.emitRunEvent({runId:t,workflowId:e.id,nodeId:n,phase:"paused",status:"paused",note:k.kind}),T&&this.kickChildWalk(T),k.kind==="timerWait")try{this.timers.schedule({runId:t,workflowId:e.id,nodeId:k.nodeId,fireAt:k.fireAt,cancelKey:`${t}:${k.nodeId}`})}catch(Ae){this.log(`[workflow:${e.id}] timer schedule failed: ${Ae.message}`)}return}let A=f.output??{},kt={...m.context,[n]:A},{nextPending:bt}=he({workflow:e,fromNodeId:n,selectedPort:f.port}),Q=[],C={...m.joinCounters??{}};for(let k of bt){let T=N(e,k);if(!(T?.type==="gateway.parallel"&&String(T.config?.mode??"fanOut")==="join")){Q.push(k);continue}let _=C[k]??[];_.includes(n)||_.push(n),C[k]=_;let St=e.edges.filter(At=>At.to===k).length;_.length>=St&&(Q.push(k),delete C[k])}let vt=[...w,...Q],M=d.type==="end",It=m.status==="running"?M?String(d.config.status??"completed"):"running":void 0,O=this.runs.recordExecution({runId:t,entry:{at:y,nodeId:n,inputKeys:l,status:"ok",output:A,idempotencyKey:i},nextPending:M?[]:vt,status:It,context:kt,joinCounters:C});this.emitRunEvent({runId:t,workflowId:e.id,nodeId:n,phase:M?"completed":"ok",status:O?.status??m.status}),f.emitSignal&&this.emitSignal({name:f.emitSignal.name,scope:f.emitSignal.scope,workflowId:e.id,payload:f.emitSignal.payload}),M&&O&&O.parentRunId&&O.parentNodeId&&this.resumeParent({parentRunId:O.parentRunId,parentNodeId:O.parentNodeId,childRun:O}).catch(k=>this.log(`[workflow:${e.id}] resumeParent failed: ${k.message}`))})}async spawnChild(e){let t=this.store.list().find(a=>a.id===e.childWorkflowId);if(!t)return null;let n=q(t);if(!n)return this.log(`[workflow:${t.id}] no trigger node \u2014 cannot spawn as child`),null;let o={...e.input};o[n.triggerId]={...o[n.triggerId]??{},parentRunId:e.parent.id,parentNodeId:e.parentNodeId};let i={backend:"agentx-internal",id:`subprocess:${e.parent.id}:${e.parentNodeId}`},s=this.runs.create({workflowId:t.id,initialPending:n.pending,entityRef:i,initialContext:o,parentRunId:e.parent.id,parentNodeId:e.parentNodeId,rootRunId:e.parent.rootRunId??e.parent.id,depth:(e.parent.depth??0)+1});return this.log(`[workflow:${t.id}] child run ${s.id} spawned from ${e.parent.id}/${e.parentNodeId} (depth ${s.depth})`),s}kickChildWalk(e){let t=this.store.list().find(n=>n.id===e.workflowId);t&&this.walk(t,e.id,`spawn:${e.parentRunId}:${e.parentNodeId}`).catch(n=>this.log(`[workflow:${t.id}] child walk failed: ${n.message}`))}async resumeParent(e){let t=this.runs.get(e.parentRunId);if(!t)return;let n=this.store.list().find(o=>o.id===t.workflowId);n&&(await this.commit(e.parentRunId,()=>{let o=this.runs.get(e.parentRunId);if(!o||o.status!=="paused"||!o.pausedAt||o.pausedAt.kind!=="subProcess"||o.pausedAt.nodeId!==e.parentNodeId||o.pausedAt.childRunId!==e.childRun.id)return;let i=N(n,e.parentNodeId),s=i?n.edges.filter(d=>d.from===i.id).map(d=>d.to):[],a={childRunId:e.childRun.id,status:e.childRun.status,output:zn(e.childRun)};this.runs.recordExecution({runId:o.id,entry:{at:new Date().toISOString(),nodeId:e.parentNodeId,inputKeys:[],status:"resumed",output:a,idempotencyKey:x(o.id,e.parentNodeId,`child:${e.childRun.id}`)},nextPending:s,status:"running",pausedAt:null,context:{...o.context,[e.parentNodeId]:a}}),this.log(`[workflow:${n.id}] parent run ${o.id} resumed from subProcess child ${e.childRun.id}`),this.emitRunEvent({runId:o.id,workflowId:n.id,nodeId:e.parentNodeId,phase:"resumed",status:"running",note:`child:${e.childRun.id}`})}),this.walk(n,e.parentRunId,`child:${e.childRun.id}`))}};function zn(r){for(let e=r.history.length-1;e>=0;e--){let t=r.history[e];if(t.status==="ok"&&t.output&&Object.keys(t.output).length>0)return t.output}return{}}function qn(r,e,t){let n=i=>{let s=r[i];if(s===void 0||s===""||s==="*")return!0;if(Array.isArray(s)){let a=new Set(e.labels??[]);return s.some(d=>a.has(String(d)))}return i==="chat"?V(e.source,String(s))===V(e.source,e.chat):e[i]===s};if(!n("source")||!n("project")||!n("repo")||!n("chat"))return!1;let o=r.eventIdLike;return!(typeof o=="string"&&o&&!t.id.includes(o))}function V(r,e){return e==null?"":r==="whatsapp-message"?e.replace(/@s\.whatsapp\.net$|@g\.us$/i,"").replace(/[\s+()]/g,""):e}function Jn(r){return{"pre:channel-message":async e=>{let t=e.msg;if(!t)return{};let n=Yn(t.channel);if(!n)return{};let o=t.group?.id??t.sender.id,i={backend:t.channel,id:`${t.channel}:${o}`},{claimed:s}=await r.dispatch({trigger:{source:n,chat:o},entityRef:i,event:{id:`${t.channel}:${t.accountId}:${t.id}`,payload:Gn(t)}});return s.length===0?{}:s.every(d=>d.nodes.find(l=>l.type.startsWith("trigger."))?.config?.passthrough===!0)?{}:{blocked:!0,message:`handled by workflow${s.length>1?"s":""}: ${s.map(d=>d.id).join(", ")}`}},"on:gitlab-issue":async e=>{let t=e.project,n=e.iid,o=e.issueEvent;if(!t||n===void 0)return{};let i=Array.isArray(o?.object_attributes?.labels)?o.object_attributes.labels.map(d=>typeof d=="string"?d:d?.title).filter(Boolean):o?.labels?.map(d=>d?.title)??[],s=o?.assignees??o?.object_attributes?.assignee_ids??[],a={backend:"gitlab",id:`${t}#${n}`};return await r.dispatch({trigger:{source:"gitlab-issue",project:t,labels:i},entityRef:a,event:{id:`gitlab-issue:${t}:${n}:${o?.object_attributes?.updated_at||o?.object_attributes?.action||"evt"}`,payload:{issue:{iid:n,title:o?.object_attributes?.title,description:o?.object_attributes?.description,url:o?.object_attributes?.url,action:o?.object_attributes?.action,labels:i,assignees:s},project:t,channel:"gitlab",chatId:`${t}:issue:${n}`}}}),{}},"on:gitlab-mr":async e=>{let t=e.project,n=e.iid,o=e.mrEvent;if(!t||n===void 0)return{};let i=Array.isArray(e.labels)?e.labels:Array.isArray(o?.object_attributes?.labels)?o.object_attributes.labels.map(c=>typeof c=="string"?c:c?.title).filter(Boolean):[],s=o?.assignees??o?.object_attributes?.assignee_ids??[],a=o?.reviewers??[],d={backend:"gitlab",id:`${t}!${n}`};return await r.dispatch({trigger:{source:"gitlab-mr",project:t,labels:i},entityRef:d,event:{id:`gitlab-mr:${t}:${n}:${o?.object_attributes?.updated_at||o?.object_attributes?.action||"evt"}`,payload:{mr:{iid:n,title:e.title,description:e.description,url:e.url,action:e.action,state:e.state,source_branch:e.source_branch,target_branch:e.target_branch,labels:i,assignees:s,reviewers:a},project:t,channel:"gitlab",chatId:`${t}:merge_request:${n}`,iid:n,title:e.title,description:e.description,url:e.url,action:e.action,state:e.state,source_branch:e.source_branch,target_branch:e.target_branch,labels:i}}}),{}},"on:gitlab-note":async e=>{let t=e.project,n=e.noteId,o=e.noteableType,i=e.noteableIid,s=e.text,a=e.authorUsername,d=e.mentions??[];if(!t||!n||!o||!i)return{};let c=o==="merge_request"?{backend:"gitlab",id:`${t}!${i}`}:{backend:"gitlab",id:`${t}#${i}`};return await r.dispatch({trigger:{source:"gitlab-note",project:t},entityRef:c,event:{id:`gitlab-note:${t}:${o}:${i}:${n}`,payload:{note:{id:n,text:s,author:a,mentions:d,noteableType:o,noteableIid:i,noteableTitle:e.noteableTitle},project:t,channel:"gitlab",chatId:`${t}:${o}:${i}`,noteId:n,noteableType:o,noteableIid:i,text:s,author:a,mentions:d}}}),{}},"on:gitlab-pipeline":async e=>{let t=e.project,n=e.pipelineId,o=e.status,i=e.ref;if(!t||!o)return{};let a=e.raw?.merge_request?.iid;if(!a)return{};let d={backend:"gitlab",id:`${t}!${a}`};return await r.dispatch({trigger:{source:"gitlab-pipeline",project:t},entityRef:d,event:{id:`gitlab-pipeline:${t}:${n}:${o}`,payload:{pipeline:{id:n,status:o,ref:i},project:t,channel:"gitlab",chatId:`${t}:merge_request:${a}`}}}),{}}}}function Yn(r){switch(r){case"telegram":return"telegram-message";case"whatsapp":return"whatsapp-message";case"discord":return"discord-message";case"slack":return"slack-message";default:return null}}function Gn(r){let e=r.group?.id??r.sender.id;return{channel:r.channel,chatId:e,accountId:r.accountId,text:r.text,fromJid:r.sender.id,sender:{id:r.sender.id,name:r.sender.name,username:r.sender.username},contact:r.channelMeta?.facts?{facts:r.channelMeta.facts}:void 0,group:r.group?{id:r.group.id,name:r.group.name}:void 0,channelMeta:r.channelMeta,replyTo:r.replyTo,replyToText:r.replyToText,media:r.media,event:{id:r.id,timestamp:r.timestamp?.toISOString?.()??new Date().toISOString()}}}var Z=r=>r.trim().toLowerCase().replace(/^@/,"");function Vn(r){let e=typeof r.author=="string"?r.author:typeof r.authorUsername=="string"?r.authorUsername:void 0;if(e)return Z(e);let n=r.payload?.sender?.login;return typeof n=="string"&&n?Z(n):void 0}function Zn(r,e){let t=typeof e.project=="string"?e.project:"";if(r==="on:gitlab-issue"||r==="on:gitlab-mr")return!t||e.iid==null?void 0:`gitlab:${t}${r==="on:gitlab-issue"?"#":"!"}${String(e.iid)}`;if(r==="on:gitlab-note"){let n=e.noteableIid!=null?String(e.noteableIid):"",o=typeof e.noteableType=="string"?e.noteableType:"";return!t||!n||!o?void 0:`gitlab:${t}${o==="issue"?"#":"!"}${n}`}if(r==="on:github-issue"||r==="on:github-pr"){let n=e.payload??{},o=typeof e.repo=="string"?e.repo:n.repository?.full_name,i=e.number??n.issue?.number??n.pull_request?.number;return typeof o!="string"||!o||i==null?void 0:`github:${o}#${String(i)}`}}function Xn(r){let e=new Set;for(let t of r.nodes){let n=t.type==="agent"?t.config.agentId:void 0;typeof n=="string"&&n&&e.add(n)}return[...e]}var X=class{constructor(e=2e3){this.maxKeys=e}fires=new Map;tryFire(e,t,n,o=Date.now()){let i=(this.fires.get(e)??[]).filter(s=>o-s<n);if(i.length>=t)return this.fires.set(e,i),!1;for(i.push(o),this.fires.delete(e),this.fires.set(e,i);this.fires.size>this.maxKeys;){let s=this.fires.keys().next().value;if(s===void 0)break;this.fires.delete(s)}return!0}get size(){return this.fires.size}};function Se(r,e,t){let n=r.logged??(r.logged=new Set);n.has(e)||(n.add(e),r.log(t))}function gt(r,e,t,n,o){let i=Vn(t);if(i&&Array.isArray(n?.ignoreAuthors)&&n.ignoreAuthors.length>0&&n.ignoreAuthors.map(Z).includes(i))return{skip:!0,reason:"ignored-author",detail:`author @${i} is in filter.ignoreAuthors`};if(n?.skipSelfAuthored===!0){let a=Xn(r),d=typeof t.authorAgent=="string"?t.authorAgent:void 0;if(d&&a.includes(d))return{skip:!0,reason:"self-authored",detail:`author @${i??"?"} is agent "${d}" which this workflow runs`};if(i){let c=new Set(a.flatMap(l=>(o.forgeUsernames?.(l)??[]).map(Z)));if(c.has(i))return{skip:!0,reason:"self-authored",detail:`author @${i} is this workflow's own bot identity`};a.length===0?Se(o,`noagents:${r.id}`,`[workflows] ${r.id} has no agent node \u2014 self-authored skip can't resolve a bot identity; only filter.ignoreAuthors applies`):c.size===0&&!("authorAgent"in t)&&Se(o,`noident:${r.id}:${e}`,`[workflows] ${r.id} no forge username known for agent(s) ${a.join(", ")} on ${e} \u2014 self-authored skip inactive; only filter.ignoreAuthors applies`)}}let s=n?.maxFiresPerTarget;if(s&&typeof s.count=="number"&&s.count>0){let a=Zn(e,t);if(a){let d=typeof s.windowMinutes=="number"&&s.windowMinutes>0?s.windowMinutes:60,c=o.now?.()??Date.now();if(!o.fireWindow.tryFire(`${r.id}|${a}`,s.count,d*6e4,c))return{skip:!0,reason:"chain-limit",detail:`${a} already fired ${s.count}x within ${d}m (filter.maxFiresPerTarget)`}}else Se(o,`notarget:${r.id}:${e}`,`[workflows] ${r.id} filter.maxFiresPerTarget has no target key for ${e} \u2014 limit not applied`)}return{skip:!1}}function Qn(r){let e=r.store.list(),t={fireWindow:new X,log:r.log,forgeUsernames:r.forgeUsernames,logged:new Set},n=0,o=0;for(let i of e){if(i.state&&i.state!=="active"){r.log(`[workflows] ${i.id} state=${i.state} \u2014 skipping trigger registration`);continue}let s=i.nodes.find(a=>a.type.startsWith("trigger."));if(s){if(s.type==="trigger.cron"){let a=s.config;if(!a.spec){r.log(`[workflows] ${i.id} trigger.cron missing config.spec \u2014 skipping`);continue}tr({workflowId:i.id,triggerNodeId:s.id,spec:a.spec,timezone:a.timezone??"UTC"},r.dispatcher,r.log),n++}else if(s.type==="trigger.hook"){let a=s.config;if(!a.event||!a.event.startsWith("on:")){r.log(`[workflows] ${i.id} trigger.hook config.event must start with "on:" \u2014 skipping`);continue}r.hooks.registerHandler(a.event,`workflows:${i.id}`,async d=>{try{let c=typeof d.project=="string"?d.project:void 0;if(i.project&&c&&i.project!==c)return{};if(a.filter){if(Array.isArray(a.filter.topic)&&a.filter.topic.length>0){let h=typeof d.topic=="string"?d.topic.toLowerCase():void 0;if(!h||!a.filter.topic.map(m=>m.toLowerCase()).includes(h))return{}}if(Array.isArray(a.filter.action)&&a.filter.action.length>0){let h=typeof d.action=="string"?d.action:void 0;if(!h||!a.filter.action.includes(h))return{}}if(Array.isArray(a.filter.mentions)&&a.filter.mentions.length>0){let h=Array.isArray(d.mentions)?d.mentions.map(w=>w.toLowerCase().replace(/^@/,"")):[];if(!a.filter.mentions.map(w=>w.toLowerCase().replace(/^@/,"")).some(w=>h.includes(w)))return{}}if(Array.isArray(a.filter.noteableType)&&a.filter.noteableType.length>0){let h=typeof d.noteableType=="string"?d.noteableType.toLowerCase():void 0,m=a.filter.noteableType.map(y=>y.toLowerCase());if(!h||!m.includes(h))return{}}if(Array.isArray(a.filter.assigneesAdded)&&a.filter.assigneesAdded.length>0){let h=Array.isArray(d.assigneesAdded)?d.assigneesAdded.map(w=>w.toLowerCase().replace(/^@/,"")):[];if(!a.filter.assigneesAdded.map(w=>w.toLowerCase().replace(/^@/,"")).some(w=>h.includes(w)))return{}}if(Array.isArray(a.filter.reviewersAdded)&&a.filter.reviewersAdded.length>0){let h=Array.isArray(d.reviewersAdded)?d.reviewersAdded.map(w=>w.toLowerCase().replace(/^@/,"")):[];if(!a.filter.reviewersAdded.map(w=>w.toLowerCase().replace(/^@/,"")).some(w=>h.includes(w)))return{}}if(Array.isArray(a.filter.labelsAdded)&&a.filter.labelsAdded.length>0){let h=Array.isArray(d.labelsAdded)?d.labelsAdded.map(w=>w.toLowerCase()):[];if(!a.filter.labelsAdded.map(w=>w.toLowerCase()).some(w=>h.includes(w)))return{}}}let l=gt(i,a.event,d,a.filter,t);if(l.skip){if(r.log(`[workflows] ${i.id} skipping ${a.event} (${l.reason}): ${l.detail}`),a.passthrough)return{};let h=d.__workflowClaimed;return{modified:{__workflowClaimed:[...Array.isArray(h)?h:[],i.id]}}}let p=er(i.id,a.event,d);if(await r.dispatcher.dispatchWorkflow({workflowId:i.id,entityRef:{backend:"hook",id:p},event:{id:`hook:${a.event}:${Date.now().toString(36)}`,payload:{hookEvent:a.event,...d}}}),a.passthrough)return{};let g=d.__workflowClaimed;return{modified:{__workflowClaimed:[...Array.isArray(g)?g:[],i.id]}}}catch(c){return r.log(`[workflows] ${i.id} hook dispatch failed: ${c.message}`),{}}},60),o++}}}return{cronTimers:n,hookSubscribers:o}}function er(r,e,t){let n=typeof t.project=="string"?t.project:"",o=t.iid!=null?String(t.iid):"";if(e==="on:gitlab-issue"&&n&&o)return`${r}:${e}:${n}#${o}`;if(e==="on:gitlab-mr"&&n&&o)return`${r}:${e}:${n}!${o}`;if(e==="on:gitlab-pipeline"&&n){let i=t.pipelineId!=null?String(t.pipelineId):"";if(i)return`${r}:${e}:${n}@pipeline:${i}`}return`${r}:${e}:${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function tr(r,e,t){let n=()=>{let o;try{o=Ce(r.spec,new Date,r.timezone)}catch(s){t(`[workflows] ${r.workflowId} cron spec invalid: ${s.message}`);return}let i=Math.max(1e3,o.getTime()-Date.now());setTimeout(()=>{(async()=>{let s=`cron:${r.workflowId}:${o.toISOString()}`;try{await e.dispatchWorkflow({workflowId:r.workflowId,trigger:{source:"cron"},entityRef:{backend:"cron",id:`${r.workflowId}@${o.toISOString()}`},event:{id:s,payload:{now:o.toISOString(),spec:r.spec,workflowId:r.workflowId}}})}catch(a){t(`[workflows] ${r.workflowId} cron dispatch failed: ${a.message}`)}finally{n()}})()},i)};n()}function mt(r){return r.nodes.find(n=>n.type.startsWith("trigger."))?.config?.inputSchema??null}function ht(r,e){if(!r||!e?.properties)return{};let t=r.match(/^([^:]+\/[^:]+):([^:]+):(.+)$/);if(!t)return{};let[,n,o,i]=t,s={};if(e.properties.project&&(s.project=n),o==="push"){let a=i.match(/^refs\/heads\/(.+)$/);a&&e.properties.ref&&(s.ref=a[1])}else{let a=Number(i);Number.isFinite(a)&&(e.properties.id&&(s.id=a),e.properties.iid&&(s.iid=a),e.properties.mrId&&(s.mrId=a),e.properties.issueId&&(s.issueId=a),e.properties.prId&&(s.prId=a))}return s}function wt(r,e){if(!r?.properties)return e;let t={...e};for(let[n,o]of Object.entries(r.properties))t[n]===void 0&&o&&"default"in o&&(t[n]=o.default);return t}function yt(r,e){return!r?.required||!Array.isArray(r.required)?[]:r.required.filter(t=>{let n=e[t];return n===void 0||n===""||n===null})}function rr(r,e){let t=mt(r);if(!t?.properties){let d={};for(let[c,l]of Object.entries(e))l!==void 0&&(d[c]=l);return{inputs:d,missing:[],filledFrom:{passthrough:Object.keys(d),chatId:[],defaults:[]}}}let n={};for(let d of["message","agentId","channel","chatId","senderId","senderUsername"])t.properties[d]&&e[d]!==void 0&&(n[d]=e[d]);let o=ht(e.chatId,t),i={...n,...o},s={...i};i=wt(t,i);let a=Object.keys(i).filter(d=>s[d]===void 0&&i[d]!==void 0);return{inputs:i,missing:yt(t,i),filledFrom:{passthrough:Object.keys(n),chatId:Object.keys(o),defaults:a}}}export{Le as a,Ke as b,$ as c,ae as d,v as e,L as f,Yt as g,le as h,fe as i,me as j,Ie as k,Jn as l,Qn as m,pn as n,rr as o};
|
|
19
|
-
//# sourceMappingURL=chunk-JUJ3TCOE.js.map
|