@desplega.ai/agent-swarm 2.13.2 → 2.13.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/acp-adapter-mr4temec.js +17 -0
- package/dist/{acp-targets-mz8c5dnt.js → acp-targets-zrk9k0n7.js} +10 -10
- package/dist/{actions-5ft3qp5a.js → actions-acqqj9jn.js} +236 -26
- package/dist/{agent-fs-provision-6fgz7wvz.js → agent-fs-provision-zmaykqnd.js} +4 -4
- package/dist/{amp-adapter-nthn8ezm.js → amp-adapter-a7ts8tmw.js} +3 -3
- package/dist/{app-535m78qw.js → app-tmwa442h.js} +7 -7
- package/dist/{approval-notifications-dewbk403.js → approval-notifications-6psaaaye.js} +8 -8
- package/dist/{assistant-39zyabv2.js → assistant-564v6emv.js} +25 -25
- package/dist/{boot-args-schema-bqv5bf77.js → boot-args-schema-n099e0f2.js} +1 -1
- package/dist/{boot-reembed-fas7z3zn.js → boot-reembed-chx66qfk.js} +1 -1
- package/dist/{boot-reembed-157c0gcz.js → boot-reembed-epvg4fp9.js} +1 -1
- package/dist/{boot-scrub-sweep-tmec0be2.js → boot-scrub-sweep-dhkfp0a7.js} +2 -2
- package/dist/{boot-seeds-32zm50x2.js → boot-seeds-m74fc07r.js} +4 -4
- package/dist/{boxd-hr8rsxzq.js → boxd-451q55ys.js} +1 -1
- package/dist/{claude-adapter-gwq7x2nj.js → claude-adapter-hw63yj3j.js} +12 -9
- package/dist/{claude-managed-adapter-rkvw6fvq.js → claude-managed-adapter-z5s7fx6p.js} +3 -3
- package/dist/{claude-managed-setup-0vgz4d1j.js → claude-managed-setup-wee1762m.js} +3 -3
- package/dist/{claude-sdk-session-5wbwxy8c.js → claude-sdk-session-cktyqkpk.js} +27 -13
- package/dist/{cli-d528acsw.js → cli-0fgvnb0x.js} +7 -7
- package/dist/{cli-2v4xxnx2.js → cli-0h8skzss.js} +1 -1
- package/dist/{cli-jkkcm72j.js → cli-0p76my9q.js} +31 -16
- package/dist/{cli-fp65jdp2.js → cli-1kvcsd2f.js} +219 -155
- package/dist/{cli-gc7jkf4a.js → cli-1vmhnncj.js} +3 -3
- package/dist/{cli-tceqvv6h.js → cli-29h5239w.js} +5 -5
- package/dist/cli-2ap1the6.js +11 -0
- package/dist/{cli-8fj8yfmk.js → cli-2vp0z049.js} +1 -1
- package/dist/{cli-ewb028rs.js → cli-3bxrrh53.js} +4 -4
- package/dist/{cli-nvqq3232.js → cli-3tzmh38q.js} +9 -9
- package/dist/{cli-0xwb7zpt.js → cli-3xqad83h.js} +2 -2
- package/dist/{cli-0f7n3td3.js → cli-3zrwrnz7.js} +1 -1
- package/dist/{cli-2wde56gv.js → cli-404am6f3.js} +7 -7
- package/dist/{cli-r4fphq38.js → cli-49aq3cyn.js} +4 -4
- package/dist/{cli-8qvte9hn.js → cli-4fpa0zns.js} +3 -3
- package/dist/{cli-x5yb8zc8.js → cli-4pbwg7sn.js} +2 -2
- package/dist/{cli-s08zsqva.js → cli-4q2c8rxw.js} +76 -10
- package/dist/{cli-3mf04tkh.js → cli-4vynxtrb.js} +1 -1
- package/dist/{cli-tbdw3f92.js → cli-5ashycw3.js} +3 -3
- package/dist/{cli-c9bwawf9.js → cli-5rgm8p39.js} +3 -3
- package/dist/{cli-g0b3ma7r.js → cli-5rxsb3wq.js} +6 -6
- package/dist/{cli-a6rzw649.js → cli-60dwk8tx.js} +3 -3
- package/dist/{cli-xhkek467.js → cli-7by7vp6m.js} +30 -4
- package/dist/{cli-62fjschk.js → cli-7g3fg4gf.js} +7 -7
- package/dist/{cli-ka13xx6b.js → cli-7gbff32z.js} +2 -2
- package/dist/{cli-q8aq48v1.js → cli-8b4rpnwj.js} +1 -1
- package/dist/{cli-1f48qdnb.js → cli-8cas2xvp.js} +3 -3
- package/dist/{cli-dnvmwsvc.js → cli-904wk98s.js} +799 -371
- package/dist/{cli-m1wddksc.js → cli-93n305hm.js} +2 -2
- package/dist/{cli-31vt7baf.js → cli-944w9wb4.js} +21 -17
- package/dist/{cli-je587f74.js → cli-94gx6ze9.js} +1 -1
- package/dist/{cli-fcwrd7bh.js → cli-9ah37a8a.js} +6 -6
- package/dist/{cli-rfejbpe1.js → cli-akm6y2a8.js} +1 -1
- package/dist/{cli-f8rcvf2x.js → cli-azj9t1f9.js} +37 -2
- package/dist/{cli-mwxez0pz.js → cli-b768ek79.js} +1 -1
- package/dist/{cli-cmgdptmx.js → cli-bv4vvnmg.js} +31 -7
- package/dist/{cli-1gevjrc1.js → cli-bzcwwebm.js} +1 -1
- package/dist/{cli-sjk85d7v.js → cli-cq4am6vg.js} +3 -3
- package/dist/{cli-f1sdh8ca.js → cli-d5pc8ep0.js} +103 -9
- package/dist/{cli-7m6bbtab.js → cli-ea7nz50q.js} +12 -12
- package/dist/{cli-zkbz8m2q.js → cli-fkpnx3vf.js} +1 -1
- package/dist/{cli-ya1cj689.js → cli-fw67mnyc.js} +1 -1
- package/dist/{cli-5basv0e7.js → cli-gkv0r2hq.js} +1 -1
- package/dist/{cli-nkfv398a.js → cli-gse7bp3z.js} +12 -10
- package/dist/{cli-4djg31jh.js → cli-gtj12v95.js} +1 -1
- package/dist/{cli-qn79645p.js → cli-h9d3sdnc.js} +1 -1
- package/dist/{cli-tgmate57.js → cli-hdhpdrka.js} +6 -23
- package/dist/{cli-fgm2mad9.js → cli-hhtbandk.js} +2 -2
- package/dist/cli-hyqksecw.js +1907 -0
- package/dist/{cli-t25rq8mg.js → cli-ja450998.js} +40 -11
- package/dist/{cli-43dsqhcp.js → cli-jbrc98qb.js} +4 -4
- package/dist/{cli-82j36f2m.js → cli-jjzxsk47.js} +9 -3
- package/dist/{cli-xerdrnqs.js → cli-jyhbvdga.js} +3 -3
- package/dist/{cli-t9nxq30h.js → cli-jzerrzgc.js} +8 -8
- package/dist/{cli-hv3820ez.js → cli-k0nebh10.js} +1 -1
- package/dist/{cli-s6fhqbz1.js → cli-ka48vpev.js} +6 -6
- package/dist/{cli-d2epqm0y.js → cli-kezzteka.js} +1 -1
- package/dist/{cli-getrvmtx.js → cli-kj84fqxz.js} +2 -2
- package/dist/{cli-h0ewec3d.js → cli-kr0jpw9c.js} +1 -1
- package/dist/{cli-gq6qhmrr.js → cli-m1sns1da.js} +3 -3
- package/dist/{cli-bp2rt28p.js → cli-n1kjs58m.js} +5 -5
- package/dist/{cli-rvhaahfv.js → cli-nc4pbwmp.js} +9 -9
- package/dist/{cli-d0jb2qnt.js → cli-p3knvk62.js} +74 -47
- package/dist/{cli-50whymxq.js → cli-p436yrzp.js} +2 -2
- package/dist/{cli-cs26ed89.js → cli-phdzn699.js} +8 -8
- package/dist/{cli-b0kqw55g.js → cli-pz1dp12c.js} +1 -1
- package/dist/{cli-8a4qg44m.js → cli-pz1nq5xm.js} +6 -6
- package/dist/{cli-e87fg3en.js → cli-qzz6tz8s.js} +1 -1
- package/dist/{cli-69eq6gdk.js → cli-rmgvwcmy.js} +38 -29
- package/dist/{cli-5k1hvycs.js → cli-rv3y60bt.js} +4 -4
- package/dist/cli-s33bzmk0.js +27 -0
- package/dist/{cli-at67kvnp.js → cli-srktrbby.js} +1 -1
- package/dist/{cli-6rmryz03.js → cli-t0jmkcah.js} +14 -14
- package/dist/{cli-eetzmsy5.js → cli-t9pzz2eq.js} +2 -2
- package/dist/{cli-wdtqkqnq.js → cli-tr19nyn9.js} +4 -4
- package/dist/{cli-erh1rgh4.js → cli-ts5yv7dn.js} +165 -88
- package/dist/{cli-zqy28rwx.js → cli-tsc3pdfd.js} +4 -4
- package/dist/{cli-x7aqhxj5.js → cli-tzw1jr2t.js} +2 -2
- package/dist/{cli-n14r8h4n.js → cli-x2cem5vy.js} +6 -4
- package/dist/{cli-vx9acp12.js → cli-ybte1fqc.js} +1 -1
- package/dist/{cli-xysy1g8x.js → cli-ysv0k1we.js} +2 -2
- package/dist/{cli-vdfngx2g.js → cli-ywy8yz6t.js} +2 -2
- package/dist/{cli-cpkxh68d.js → cli-z1vam71h.js} +2 -2
- package/dist/{cli-zm6bkx3e.js → cli-zexwhj3f.js} +3 -3
- package/dist/{cli-j2ybkdk2.js → cli-zhwjdhjr.js} +2 -2
- package/dist/{cli-gedf48yw.js → cli-zjdhrzm0.js} +8 -8
- package/dist/cli.js +20 -20
- package/dist/{codex-adapter-x25xfbnh.js → codex-adapter-2fs2c0n6.js} +8 -8
- package/dist/{codex-hook-c0nvm30r.js → codex-hook-jxjv6dy5.js} +10 -3
- package/dist/{codex-login-ven5cz5j.js → codex-login-ktfg1cxk.js} +1 -1
- package/dist/{codex-session-runner-kn5xnrvp.js → codex-session-runner-r55tmx4c.js} +9 -9
- package/dist/{commands-8n59gxmy.js → commands-0mxdy9x8.js} +3 -3
- package/dist/{controller-wn3vd217.js → controller-g3vkfhr4.js} +4 -4
- package/dist/{controllers-connect-09gvkrhc.js → controllers-connect-4wdmncqt.js} +25 -25
- package/dist/core-gsvj5f3z.js +42 -0
- package/dist/{cursor-adapter-w1681kp1.js → cursor-adapter-t9qb96q2.js} +2 -2
- package/dist/{db-e71keqxk.js → db-487vvyv9.js} +3 -3
- package/dist/{db-spg81qtr.js → db-76p7w3gr.js} +2 -2
- package/dist/{devin-adapter-fs90ab4v.js → devin-adapter-3bp6rape.js} +1 -1
- package/dist/{dispatcher-fr4vawwb.js → dispatcher-64rp6w67.js} +22 -22
- package/dist/{docker-1h33jvh9.js → docker-a59g3ebm.js} +2 -2
- package/dist/{dsh-adapter-g9yqv09y.js → dsh-adapter-8abzqk5c.js} +2 -2
- package/dist/{e2b-y7e5kmzf.js → e2b-3ykbe805.js} +2 -2
- package/dist/{e2b-jnk0yeva.js → e2b-dc8f6ctq.js} +2 -2
- package/dist/{easter-egg-3d-ac9tv9a6.js → easter-egg-3d-jrrwyf55.js} +1 -1
- package/dist/{embedding-space-an77f45k.js → embedding-space-001hhhpk.js} +6 -6
- package/dist/{embeddings-jkrehejr.js → embeddings-esj19cnw.js} +1 -1
- package/dist/{event-bus-08t2b4y2.js → event-bus-7gbsr0g4.js} +1 -1
- package/dist/{execute-3mys4nta.js → execute-301hkxqg.js} +1 -1
- package/dist/{external-channel-s6zxpts9.js → external-channel-w10e2j05.js} +2 -2
- package/dist/fx-adapter-4sjrbdne.js +20 -0
- package/dist/grok-adapter-3a0ezfee.js +20 -0
- package/dist/handlers-ef3k11hb.js +41 -0
- package/dist/{heartbeat-jjpb44e5.js → heartbeat-tbrj7vhq.js} +25 -25
- package/dist/hook-3am1sq68.js +22 -0
- package/dist/{hook-y6n23zzj.js → hook-tx917rqw.js} +11 -8
- package/dist/{http-8c6y008s.js → http-3rmemtqy.js} +340 -1841
- package/dist/{index-mbpxhc4w.js → index-126v2d0t.js} +1 -4
- package/dist/{index-xcw7hjt5.js → index-2jw11t8s.js} +26 -26
- package/dist/{index-p2f5xg64.js → index-3j803vnb.js} +36259 -34299
- package/dist/{index-we3nd2t0.js → index-aetfyx6p.js} +1 -1
- package/dist/index-e6bq0exk.js +42 -0
- package/dist/{index-0vthtbc2.js → index-gfnq66t1.js} +231 -25
- package/dist/index-hf2k1vge.js +39 -0
- package/dist/{index-6h3r0vpe.js → index-s7xtvc0f.js} +1 -1
- package/dist/index-taxmejj3.js +44 -0
- package/dist/{k8s-8326q0rq.js → k8s-36gfn847.js} +2 -2
- package/dist/{keepalive-7e9r5dvp.js → keepalive-9px3t7qj.js} +5 -5
- package/dist/lead-5vt6f174.js +83 -0
- package/dist/{maintenance-d3erjvcg.js → maintenance-vwqjwst6.js} +1 -1
- package/dist/{oauth-refresh-sweep-0qh70988.js → oauth-refresh-sweep-yqry3wn4.js} +4 -4
- package/dist/{object-webhooks-ac7v2q5p.js → object-webhooks-8s1wtths.js} +7 -7
- package/dist/{onboard-5yphtken.js → onboard-hb8czx0p.js} +7 -7
- package/dist/{opencode-adapter-0xvyba4m.js → opencode-adapter-djd6m6dk.js} +8 -8
- package/dist/{otel-impl-svqp691q.js → otel-impl-2ymwyczz.js} +2 -2
- package/dist/{pending-bn4xe5br.js → pending-nxavtvx7.js} +23 -23
- package/dist/{pi-mono-adapter-763s8a3w.js → pi-mono-adapter-d2cpmcy4.js} +13 -13
- package/dist/{pricing-refresh-kfc215mf.js → pricing-refresh-1yz8jkqv.js} +2 -2
- package/dist/{rbac-roles-6r4h2ghj.js → rbac-roles-7s6m31xw.js} +6 -4
- package/dist/{rbac-roles-3bznvkpt.js → rbac-roles-dbpx0x9v.js} +3 -3
- package/dist/{render-v2-f3qedbpy.js → render-v2-7y20rjrn.js} +7 -7
- package/dist/{resume-vcag4ann.js → resume-wz546x47.js} +10 -10
- package/dist/{runtime-x0s55z2t.js → runtime-cb5bd9tz.js} +1 -1
- package/dist/{session-access-nwzve8q2.js → session-access-4vcft8kq.js} +5 -5
- package/dist/{session-source-backfill-jpqfzmgz.js → session-source-backfill-57b50tpw.js} +3 -3
- package/dist/{setup-d2smwaem.js → setup-e1tevjyj.js} +1 -1
- package/dist/thread-buffer-686pa1p1.js +42 -0
- package/dist/{tree-visibility-dwzc8en0.js → tree-visibility-07wf1nct.js} +2 -2
- package/dist/{user-merge-jobs-4ce7kma2.js → user-merge-jobs-n20qpv6s.js} +3 -3
- package/dist/{virtual-modules-78a6yw71.js → virtual-modules-6fxmn1yv.js} +3 -3
- package/dist/{work-objects-m0w1e7q8.js → work-objects-eg7y48pe.js} +25 -25
- package/dist/worker-4vp616ms.js +83 -0
- package/dist/{worker-follow-up-e3t6f895.js → worker-follow-up-jnvnnf2b.js} +22 -22
- package/dist/{x-asbrnafg.js → x-d27jj7z7.js} +2 -2
- package/openapi.json +478 -28
- package/package.json +3 -3
- package/src/be/db/approvals.ts +2 -0
- package/src/be/db/runtime.ts +5 -0
- package/src/be/db/script-run-sources.ts +17 -0
- package/src/be/db-retention.ts +1 -1
- package/src/be/db.ts +71 -62
- package/src/be/design-system.ts +63 -0
- package/src/be/migrations/342_script_run_sources.sql +20 -0
- package/src/be/migrations/runner.ts +8 -0
- package/src/be/migrations/script-run-sources.ts +51 -0
- package/src/be/rbac-roles.ts +2 -0
- package/src/be/scripts/typecheck.ts +4 -2
- package/src/be/seed-scripts/catalog/design-system-seed.ts +158 -0
- package/src/be/seed-scripts/index.ts +9 -0
- package/src/be/swarm-config-guard.ts +21 -1
- package/src/commands/onboard/agent-fs-version.ts +1 -1
- package/src/commands/runner.ts +62 -6
- package/src/heartbeat/heartbeat.ts +18 -4
- package/src/hooks/codex-hook.ts +15 -4
- package/src/hooks/hook.ts +7 -0
- package/src/http/all-routes.ts +1 -0
- package/src/http/approval-chat-answer.ts +99 -0
- package/src/http/approval-requests.ts +280 -225
- package/src/http/design-system.ts +103 -0
- package/src/http/index.ts +10 -6
- package/src/http/pages-public.ts +25 -10
- package/src/http/pages.ts +17 -0
- package/src/http/person-responder.ts +28 -0
- package/src/http/session-cost-recompute.ts +3 -1
- package/src/http/session-data.ts +3 -0
- package/src/integrations/chat-sdk/adapters.ts +33 -3
- package/src/integrations/chat-sdk/inbound.ts +6 -18
- package/src/integrations/chat-sdk/mentions.ts +188 -0
- package/src/integrations/chat-sdk/outbound.ts +20 -3
- package/src/integrations/chat-sdk/router.ts +8 -0
- package/src/integrations/chat-sdk/telegram-thread.ts +12 -0
- package/src/jira/adf.ts +35 -9
- package/src/kv-reserved-namespaces.ts +5 -0
- package/src/pages/page-head.ts +11 -1
- package/src/prompts/base-prompt.ts +1 -1
- package/src/prompts/session-templates.ts +1 -1
- package/src/providers/acp-targets.ts +2 -2
- package/src/providers/amp-adapter.ts +1 -1
- package/src/providers/claude-adapter.ts +21 -1
- package/src/providers/claude-sdk-session.ts +22 -3
- package/src/providers/claude-session-events.ts +76 -1
- package/src/providers/cursor-adapter.ts +1 -1
- package/src/providers/dsh-adapter.ts +48 -13
- package/src/providers/fx-adapter.ts +2 -2
- package/src/providers/pricing-sources.md +3 -0
- package/src/providers/types.ts +13 -0
- package/src/rbac/legacy-policy.ts +4 -0
- package/src/rbac/permissions.ts +8 -0
- package/src/scheduler/index.ts +1 -0
- package/src/scheduler/scheduler.test.ts +32 -1
- package/src/scheduler/scheduler.ts +24 -1
- package/src/script-workflows/executor.ts +6 -0
- package/src/script-workflows/supervisor.ts +2 -1
- package/src/scripts-runtime/sdk-allowlist.ts +2 -0
- package/src/scripts-runtime/swarm-sdk.ts +12 -23
- package/src/scripts-runtime/types/stdlib.d.ts +4 -1
- package/src/scripts-runtime/types/swarm-sdk.d.ts +4 -1
- package/src/server.ts +2 -0
- package/src/slack/actions.ts +3 -0
- package/src/slack/approval-actions.ts +148 -0
- package/src/slack/approval-buttons.ts +28 -0
- package/src/slack/render-v2.ts +27 -7
- package/src/tests/base-prompt.test.ts +6 -2
- package/src/tests/chat-sdk-mentions.test.ts +183 -0
- package/src/tests/claude-adapter.test.ts +115 -0
- package/src/tests/create-page-tool.test.ts +5 -0
- package/src/tests/dsh-adapter.test.ts +53 -1
- package/src/tests/fixtures/compiled-source-schema-boot.ts +24 -0
- package/src/tests/fixtures/fx/acp-updates-recorded.jsonl +1 -1
- package/src/tests/fixtures/secret-corpus.ts +43 -1
- package/src/tests/heartbeat-stall-thresholds.test.ts +174 -0
- package/src/tests/internal-ai/complete-structured.test.ts +105 -0
- package/src/tests/internal-ai/credentials.test.ts +149 -0
- package/src/tests/internal-ai/task-title.test.ts +78 -0
- package/src/tests/jira-adf.test.ts +42 -2
- package/src/tests/mcp-input-caps.test.ts +16 -11
- package/src/tests/merge-gate-detect-changes.test.ts +208 -16
- package/src/tests/migration-342-script-run-sources.test.ts +196 -0
- package/src/tests/migration-bunfs-compat.test.ts +129 -9
- package/src/tests/rbac-e2e-helpers.test.ts +10 -4
- package/src/tests/rbac-e2e-helpers.ts +13 -4
- package/src/tests/rbac-roles.test.ts +2 -0
- package/src/tests/runner-slot-reconcile.test.ts +102 -0
- package/src/tests/runtime-e2b-pools.test.ts +7 -1
- package/src/tests/schedule-target-type.test.ts +4 -1
- package/src/tests/script-connections.test.ts +2 -0
- package/src/tests/script-runs-retention.test.ts +43 -16
- package/src/tests/script-workflows-runtime-e2e.test.ts +56 -22
- package/src/tests/scripts-http.test.ts +9 -3
- package/src/tests/sdk-allowlist.test.ts +26 -13
- package/src/tests/sdk-store-progress-skipped.test.ts +12 -5
- package/src/tests/secret-rules.test.ts +34 -0
- package/src/tests/secret-scrub-gate.test.ts +7 -0
- package/src/tests/secret-scrubber.test.ts +62 -2
- package/src/tests/seed-scripts.test.ts +2 -2
- package/src/tests/slack-render-v2.test.ts +85 -0
- package/src/tests/system-one-hosts-ui-mirror.test.ts +1 -0
- package/src/tests/vcs-azure-devops.test.ts +10 -0
- package/src/tests/vcs-provider.test.ts +8 -0
- package/src/themes/design-system.ts +163 -0
- package/src/themes/page-theme.ts +28 -19
- package/src/tools/chat-post.ts +7 -3
- package/src/tools/create-page.ts +3 -0
- package/src/tools/design-system.ts +102 -0
- package/src/tools/mcp-servers/mcp-server-get.ts +1 -1
- package/src/tools/mcp-servers/mcp-server-list.ts +1 -1
- package/src/tools/register-chat-channel.ts +11 -2
- package/src/tools/skills/skill-get-file.ts +1 -1
- package/src/tools/skills/skill-get.ts +1 -1
- package/src/tools/skills/skill-list.ts +1 -1
- package/src/tools/skills/skill-search.ts +1 -1
- package/src/tools/utils.ts +49 -4
- package/src/tools/workflows/get-workflow-run.ts +1 -1
- package/src/tools/workflows/get-workflow.ts +1 -1
- package/src/tools/workflows/list-workflow-runs.ts +1 -1
- package/src/tools/workflows/list-workflows.ts +1 -1
- package/src/types.ts +67 -1
- package/src/utils/internal-ai/complete-structured.ts +36 -5
- package/src/utils/internal-ai/credentials.ts +78 -2
- package/src/utils/internal-ai/models.ts +37 -1
- package/src/utils/internal-ai/task-title.ts +31 -1
- package/src/utils/secret-rules.generated.ts +149 -149
- package/src/utils/secret-scrubber.ts +111 -5
- package/src/vcs/azure-devops.ts +22 -1
- package/src/vcs/index.ts +3 -1
- package/src/workflows/approval-inline.ts +122 -0
- package/src/workflows/approval-notifications.ts +7 -2
- package/src/workflows/engine.ts +6 -5
- package/src/workflows/executors/agent-task.ts +14 -0
- package/src/workflows/executors/system-one-providers.ts +23 -0
- package/templates/skills/pages/content.md +34 -8
- package/templates/skills/swarm-docs/content.md +13 -0
- package/templates/skills/workflow-iterate/content.md +1 -1
- package/dist/acp-adapter-x1qqgzwx.js +0 -17
- package/dist/cli-n46d87mj.js +0 -98
- package/dist/core-2b8bv6ny.js +0 -42
- package/dist/fx-adapter-4yet1c4f.js +0 -20
- package/dist/grok-adapter-8ge6tw7m.js +0 -20
- package/dist/handlers-0r9evrdj.js +0 -41
- package/dist/hook-68gbs87k.js +0 -19
- package/dist/index-1v23363p.js +0 -39
- package/dist/index-30qw6vyw.js +0 -44
- package/dist/index-6bm3w6cn.js +0 -40
- package/dist/lead-3jpc7kcr.js +0 -79
- package/dist/thread-buffer-8fc703jc.js +0 -42
- package/dist/worker-3p2vq107.js +0 -79
|
@@ -0,0 +1,1907 @@
|
|
|
1
|
+
import {
|
|
2
|
+
getDbClient2,
|
|
3
|
+
slackContextKey,
|
|
4
|
+
init_context_key,
|
|
5
|
+
USER_FUNCTIONS,
|
|
6
|
+
reportedUserFunction,
|
|
7
|
+
init_company_profile,
|
|
8
|
+
TELEMETRY_PROXY_ORIGIN,
|
|
9
|
+
normalizeOrgWebsite,
|
|
10
|
+
orgLogoUrl,
|
|
11
|
+
isFilledOrgLogoUrl,
|
|
12
|
+
init_org_website,
|
|
13
|
+
getRequestAuth,
|
|
14
|
+
authUserId,
|
|
15
|
+
authUser,
|
|
16
|
+
init_request_auth_context,
|
|
17
|
+
isTelemetryEnabled,
|
|
18
|
+
trackRelayed,
|
|
19
|
+
telemetry,
|
|
20
|
+
init_telemetry,
|
|
21
|
+
isRbacEnabled,
|
|
22
|
+
can,
|
|
23
|
+
init_rbac,
|
|
24
|
+
TELEMETRY_RANKING_KEY,
|
|
25
|
+
PUBLIC_RANKING_ENABLED_KEY,
|
|
26
|
+
RANKING_CATEGORIES,
|
|
27
|
+
readTelemetryRanking,
|
|
28
|
+
rankingFormSchema,
|
|
29
|
+
buildListing,
|
|
30
|
+
init_telemetry_ranking,
|
|
31
|
+
isSlackIconConfigKey,
|
|
32
|
+
init_reaction_shortcode,
|
|
33
|
+
isApiOnlyConfigKey,
|
|
34
|
+
isInternalConfigKey,
|
|
35
|
+
internalConfigKeyError,
|
|
36
|
+
isHumanOnlyConfigKey,
|
|
37
|
+
humanOnlyConfigKeyError,
|
|
38
|
+
humanOnlyConfigKeyPageError,
|
|
39
|
+
validateConfigEntry,
|
|
40
|
+
init_swarm_config_guard,
|
|
41
|
+
getLeadAgent2,
|
|
42
|
+
runtimeReadsRepoSecrets,
|
|
43
|
+
init_model_profile_check,
|
|
44
|
+
getTaskById2,
|
|
45
|
+
modelProfileRefError,
|
|
46
|
+
init_model_profiles,
|
|
47
|
+
listApprovalRequestSummaries2,
|
|
48
|
+
getPendingApprovalVoteState2,
|
|
49
|
+
recordApprovalVotes2,
|
|
50
|
+
maskSecrets2,
|
|
51
|
+
getSwarmConfigs2,
|
|
52
|
+
getSwarmConfigById2,
|
|
53
|
+
getSwarmConfigLookupById2,
|
|
54
|
+
upsertSwarmConfig2,
|
|
55
|
+
deleteSwarmConfig2,
|
|
56
|
+
getResolvedConfig2,
|
|
57
|
+
getWorkflowRun2,
|
|
58
|
+
getWorkflowRunStep2,
|
|
59
|
+
createApprovalRequest2,
|
|
60
|
+
getApprovalRequestById2,
|
|
61
|
+
resolveApprovalRequest2,
|
|
62
|
+
listApprovalRequests2,
|
|
63
|
+
init_db4
|
|
64
|
+
} from "./cli-ts5yv7dn.js";
|
|
65
|
+
import {
|
|
66
|
+
getUserGrant2,
|
|
67
|
+
init_rbac_roles
|
|
68
|
+
} from "./cli-x2cem5vy.js";
|
|
69
|
+
import {
|
|
70
|
+
workflowEventBus2,
|
|
71
|
+
init_event_bus
|
|
72
|
+
} from "./cli-ybte1fqc.js";
|
|
73
|
+
import {
|
|
74
|
+
getTaskUiSpec,
|
|
75
|
+
reserveTaskUiActionRun,
|
|
76
|
+
releaseTaskUiActionRun,
|
|
77
|
+
setTaskUiActionResult,
|
|
78
|
+
init_task_ui_spec
|
|
79
|
+
} from "./cli-rmgvwcmy.js";
|
|
80
|
+
import {
|
|
81
|
+
AGENT_MAX_TASKS_CONFIG_KEY,
|
|
82
|
+
resetAgentMaxTasksMirror,
|
|
83
|
+
upsertSwarmConfigWithPolicyMirror,
|
|
84
|
+
init_multi_runtime,
|
|
85
|
+
ConfigQuestionSettingsSchema,
|
|
86
|
+
ConfigStateSchema,
|
|
87
|
+
readConfigState,
|
|
88
|
+
normalizeApprovalQuestions,
|
|
89
|
+
isConfigQuestion,
|
|
90
|
+
parseConfigAnswer,
|
|
91
|
+
skippedConfigResult,
|
|
92
|
+
keptConfigResult,
|
|
93
|
+
applyConfigAnswer,
|
|
94
|
+
init_approval_config_question,
|
|
95
|
+
dispatchApprovalNotifications2,
|
|
96
|
+
createApprovalFollowUpTask2,
|
|
97
|
+
init_approval_notifications
|
|
98
|
+
} from "./cli-d5pc8ep0.js";
|
|
99
|
+
import {
|
|
100
|
+
createTaskWithSiblingAwareness,
|
|
101
|
+
init_sibling_awareness,
|
|
102
|
+
reloadGlobalConfigsAndIntegrations2,
|
|
103
|
+
scheduleIntegrationsReload2,
|
|
104
|
+
init_core,
|
|
105
|
+
runTaskUiScriptAction,
|
|
106
|
+
init_script_actions,
|
|
107
|
+
cancelApprovalRequest,
|
|
108
|
+
init_approval_cancel,
|
|
109
|
+
requestPrincipal,
|
|
110
|
+
agentFirstPrincipal,
|
|
111
|
+
init_request_principal
|
|
112
|
+
} from "./cli-904wk98s.js";
|
|
113
|
+
import {
|
|
114
|
+
duplicateGuardedQueryKey,
|
|
115
|
+
jsonError,
|
|
116
|
+
init_utils2,
|
|
117
|
+
resolveTaskAuditUserId,
|
|
118
|
+
init_audit_user,
|
|
119
|
+
resolveHttpFavoriteOwner,
|
|
120
|
+
init_favorite_owner,
|
|
121
|
+
bodyTask,
|
|
122
|
+
route,
|
|
123
|
+
init_route_def
|
|
124
|
+
} from "./cli-404am6f3.js";
|
|
125
|
+
import {
|
|
126
|
+
ORG_IDENTITY_KEYS,
|
|
127
|
+
orgIdentityStatus,
|
|
128
|
+
init_org_identity
|
|
129
|
+
} from "./cli-s33bzmk0.js";
|
|
130
|
+
import {
|
|
131
|
+
findUserById,
|
|
132
|
+
isScriptRunToken,
|
|
133
|
+
init_users
|
|
134
|
+
} from "./cli-kj84fqxz.js";
|
|
135
|
+
import {
|
|
136
|
+
SwarmConfigSchema,
|
|
137
|
+
init_types5
|
|
138
|
+
} from "./cli-azj9t1f9.js";
|
|
139
|
+
import {
|
|
140
|
+
init_zod
|
|
141
|
+
} from "./cli-96234j5w.js";
|
|
142
|
+
import {
|
|
143
|
+
ZodError,
|
|
144
|
+
string2,
|
|
145
|
+
number2,
|
|
146
|
+
boolean,
|
|
147
|
+
unknown,
|
|
148
|
+
array2,
|
|
149
|
+
object2,
|
|
150
|
+
union3,
|
|
151
|
+
record2,
|
|
152
|
+
_enum2,
|
|
153
|
+
literal2,
|
|
154
|
+
exports_coerce
|
|
155
|
+
} from "./cli-qrzq3hvg.js";
|
|
156
|
+
import {
|
|
157
|
+
isEnvFlagEnabled,
|
|
158
|
+
init_env_flag
|
|
159
|
+
} from "./cli-cebvbc9t.js";
|
|
160
|
+
import {
|
|
161
|
+
scrubSecrets,
|
|
162
|
+
registerVolatileSecret,
|
|
163
|
+
init_secret_scrubber
|
|
164
|
+
} from "./cli-1kvcsd2f.js";
|
|
165
|
+
import {
|
|
166
|
+
__esm
|
|
167
|
+
} from "./cli-242037k3.js";
|
|
168
|
+
|
|
169
|
+
// src/be/org-profile.ts
|
|
170
|
+
async function globalValue(key) {
|
|
171
|
+
const stored = (await getSwarmConfigs2({ scope: "global", key }))?.[0]?.value?.trim();
|
|
172
|
+
return stored || process.env[key]?.trim() || "";
|
|
173
|
+
}
|
|
174
|
+
async function fillOrgLogoFromWebsite(website) {
|
|
175
|
+
const host = normalizeOrgWebsite(website);
|
|
176
|
+
if (!host)
|
|
177
|
+
return false;
|
|
178
|
+
const current = await globalValue(LOGO_KEY);
|
|
179
|
+
if (current && !(isFilledOrgLogoUrl(current) && current === await globalValue(FILLED_LOGO_KEY))) {
|
|
180
|
+
return false;
|
|
181
|
+
}
|
|
182
|
+
const next = orgLogoUrl(host);
|
|
183
|
+
if (current === next)
|
|
184
|
+
return false;
|
|
185
|
+
await upsertSwarmConfig2({ scope: "global", key: LOGO_KEY, value: next, isSecret: false });
|
|
186
|
+
await upsertSwarmConfig2({ scope: "global", key: FILLED_LOGO_KEY, value: next, isSecret: false });
|
|
187
|
+
return true;
|
|
188
|
+
}
|
|
189
|
+
var LOGO_KEY = "SWARM_ORG_LOGO_URL", FILLED_LOGO_KEY = "SWARM_ORG_LOGO_FILLED_URL";
|
|
190
|
+
var init_org_profile = __esm(() => {
|
|
191
|
+
init_org_website();
|
|
192
|
+
init_db4();
|
|
193
|
+
});
|
|
194
|
+
|
|
195
|
+
// src/http/global-config.ts
|
|
196
|
+
async function globalConfig(key) {
|
|
197
|
+
const stored = (await getSwarmConfigs2({ scope: "global", key }))?.[0]?.value;
|
|
198
|
+
return (stored ?? process.env[key])?.trim() || undefined;
|
|
199
|
+
}
|
|
200
|
+
var init_global_config = __esm(() => {
|
|
201
|
+
init_db4();
|
|
202
|
+
});
|
|
203
|
+
|
|
204
|
+
// src/http/used-by.ts
|
|
205
|
+
async function telemetryProxyEndpoint(path) {
|
|
206
|
+
const feedback = await globalConfig("feedback_endpoint");
|
|
207
|
+
if (feedback && /^https?:\/\/[^/]+\/v1\/feedback\/?$/.test(feedback)) {
|
|
208
|
+
return feedback.replace(/\/v1\/feedback\/?$/, path);
|
|
209
|
+
}
|
|
210
|
+
return `${TELEMETRY_PROXY_ORIGIN}${path}`;
|
|
211
|
+
}
|
|
212
|
+
function usedByEndpoint() {
|
|
213
|
+
return telemetryProxyEndpoint("/v1/used-by");
|
|
214
|
+
}
|
|
215
|
+
async function handleUsedBy(req, res, pathSegments, queryParams, myAgentId) {
|
|
216
|
+
if (!usedBy.match(req.method, pathSegments))
|
|
217
|
+
return false;
|
|
218
|
+
const parsed = await usedBy.parse(req, res, pathSegments, queryParams);
|
|
219
|
+
if (!parsed)
|
|
220
|
+
return true;
|
|
221
|
+
if (!await ensureConfigAdmin(req, res, "config.write.any"))
|
|
222
|
+
return true;
|
|
223
|
+
const { granted, contactEmail, contactFunction, quote } = parsed.body;
|
|
224
|
+
const current = orgIdentityStatus({
|
|
225
|
+
SWARM_ORG_NAME: await globalConfig("SWARM_ORG_NAME"),
|
|
226
|
+
SWARM_ORG_WEBSITE: await globalConfig("SWARM_ORG_WEBSITE")
|
|
227
|
+
});
|
|
228
|
+
const currentName = current.name ?? undefined;
|
|
229
|
+
const currentWebsite = current.website;
|
|
230
|
+
const grantedName = granted ? undefined : await globalConfig(GRANTED_NAME_KEY);
|
|
231
|
+
const grantedWebsite = granted ? null : normalizeOrgWebsite(await globalConfig(GRANTED_WEBSITE_KEY));
|
|
232
|
+
const [orgName, orgWebsite] = grantedName && grantedWebsite ? [grantedName, grantedWebsite] : [currentName, currentWebsite];
|
|
233
|
+
if (!orgName || !orgWebsite) {
|
|
234
|
+
jsonError(res, "Set the organization name and website first", 400);
|
|
235
|
+
return true;
|
|
236
|
+
}
|
|
237
|
+
const installId = isTelemetryEnabled() ? await globalConfig("telemetry_installation_id") : undefined;
|
|
238
|
+
const orgDomain = await globalConfig("telemetry_org_domain");
|
|
239
|
+
const changedAt = new Date().toISOString();
|
|
240
|
+
try {
|
|
241
|
+
const response = await fetch(await usedByEndpoint(), {
|
|
242
|
+
method: "POST",
|
|
243
|
+
headers: { "Content-Type": "application/json" },
|
|
244
|
+
body: JSON.stringify({
|
|
245
|
+
...installId ? { install_id: installId } : {},
|
|
246
|
+
org_name: orgName,
|
|
247
|
+
org_website: orgWebsite,
|
|
248
|
+
...orgDomain ? { org_domain: orgDomain } : {},
|
|
249
|
+
granted,
|
|
250
|
+
...granted ? {
|
|
251
|
+
contact_email: contactEmail,
|
|
252
|
+
contact_function: reportedUserFunction(contactFunction),
|
|
253
|
+
quote
|
|
254
|
+
} : {},
|
|
255
|
+
changed_at: changedAt
|
|
256
|
+
}),
|
|
257
|
+
signal: AbortSignal.timeout(TIMEOUT_MS)
|
|
258
|
+
});
|
|
259
|
+
if (!response.ok) {
|
|
260
|
+
jsonError(res, `The telemetry proxy answered ${response.status}`, 502);
|
|
261
|
+
return true;
|
|
262
|
+
}
|
|
263
|
+
} catch {
|
|
264
|
+
jsonError(res, "Could not reach the telemetry proxy", 502);
|
|
265
|
+
return true;
|
|
266
|
+
}
|
|
267
|
+
await getDbClient2().transaction(async () => {
|
|
268
|
+
await upsertSwarmConfig2({ scope: "global", key: CONSENT_KEY, value: String(granted) });
|
|
269
|
+
await upsertSwarmConfig2({ scope: "global", key: CONSENT_AT_KEY, value: changedAt });
|
|
270
|
+
if (granted) {
|
|
271
|
+
await upsertSwarmConfig2({ scope: "global", key: GRANTED_NAME_KEY, value: orgName });
|
|
272
|
+
await upsertSwarmConfig2({ scope: "global", key: GRANTED_WEBSITE_KEY, value: orgWebsite });
|
|
273
|
+
}
|
|
274
|
+
for (const [key, value, isSecret] of [
|
|
275
|
+
[CONTACT_EMAIL_KEY, contactEmail, true],
|
|
276
|
+
[CONTACT_FUNCTION_KEY, contactFunction, false],
|
|
277
|
+
[QUOTE_KEY, quote, false]
|
|
278
|
+
]) {
|
|
279
|
+
await upsertSwarmConfig2({
|
|
280
|
+
scope: "global",
|
|
281
|
+
key,
|
|
282
|
+
value: granted ? value ?? "" : "",
|
|
283
|
+
isSecret,
|
|
284
|
+
exportToEnv: false
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
});
|
|
288
|
+
scheduleIntegrationsReload2();
|
|
289
|
+
const owner = await resolveHttpFavoriteOwner(req, myAgentId);
|
|
290
|
+
trackRelayed("used_by.consent_changed", {
|
|
291
|
+
granted,
|
|
292
|
+
has_quote: granted && Boolean(quote),
|
|
293
|
+
has_function: granted && Boolean(contactFunction)
|
|
294
|
+
}, { actor: owner?.userId ? { userId: owner.userId } : undefined, emitter: "ui" });
|
|
295
|
+
usedBy.respond(res, 200, { granted, changedAt });
|
|
296
|
+
return true;
|
|
297
|
+
}
|
|
298
|
+
var CONSENT_KEY = "SWARM_USED_BY_CONSENT", CONSENT_AT_KEY = "SWARM_USED_BY_CONSENT_AT", GRANTED_NAME_KEY = "SWARM_USED_BY_ORG_NAME", GRANTED_WEBSITE_KEY = "SWARM_USED_BY_ORG_WEBSITE", CONTACT_EMAIL_KEY = "SWARM_USED_BY_CONTACT_EMAIL", CONTACT_FUNCTION_KEY = "SWARM_USED_BY_CONTACT_FUNCTION", QUOTE_KEY = "SWARM_USED_BY_QUOTE", TIMEOUT_MS = 1e4, usedBy;
|
|
299
|
+
var init_used_by = __esm(() => {
|
|
300
|
+
init_zod();
|
|
301
|
+
init_db4();
|
|
302
|
+
init_telemetry();
|
|
303
|
+
init_company_profile();
|
|
304
|
+
init_org_identity();
|
|
305
|
+
init_org_website();
|
|
306
|
+
init_config();
|
|
307
|
+
init_core();
|
|
308
|
+
init_favorite_owner();
|
|
309
|
+
init_global_config();
|
|
310
|
+
init_route_def();
|
|
311
|
+
init_utils2();
|
|
312
|
+
usedBy = route({
|
|
313
|
+
method: "post",
|
|
314
|
+
path: "/api/used-by",
|
|
315
|
+
pattern: ["api", "used-by"],
|
|
316
|
+
summary: "Grant or revoke the 'used by' logo consent",
|
|
317
|
+
description: "Records consent to show the organization's logo on agent-swarm.dev. A grant requires a valid contact email. It sends organization identity, contact details, and an optional quote to the proxy for manual review. This explicit admin action works when telemetry is off. A revoke clears the stored contact details and quote.",
|
|
318
|
+
tags: ["Telemetry"],
|
|
319
|
+
body: object2({
|
|
320
|
+
granted: boolean(),
|
|
321
|
+
contactEmail: string2().max(320, "Contact email must be at most 320 characters").email("Contact email must be a valid email address").optional(),
|
|
322
|
+
contactFunction: _enum2(USER_FUNCTIONS).optional(),
|
|
323
|
+
quote: string2().max(280).optional()
|
|
324
|
+
}).refine((body) => !body.granted || body.contactEmail !== undefined, {
|
|
325
|
+
path: ["contactEmail"],
|
|
326
|
+
message: "Contact email is required when granting logo consent"
|
|
327
|
+
}),
|
|
328
|
+
responses: {
|
|
329
|
+
200: {
|
|
330
|
+
description: "Consent recorded",
|
|
331
|
+
schema: object2({ granted: boolean(), changedAt: string2() })
|
|
332
|
+
},
|
|
333
|
+
400: {
|
|
334
|
+
description: "Invalid contact details, or missing organization name or website"
|
|
335
|
+
},
|
|
336
|
+
401: { description: "Unauthorized" },
|
|
337
|
+
403: { description: "Only a config admin can change the consent" },
|
|
338
|
+
502: { description: "The telemetry proxy did not accept the consent" }
|
|
339
|
+
},
|
|
340
|
+
rbac: { permission: "config.write.any" }
|
|
341
|
+
});
|
|
342
|
+
});
|
|
343
|
+
|
|
344
|
+
// src/http/ranking.ts
|
|
345
|
+
async function currentIdentity(changed) {
|
|
346
|
+
const read = async (key) => changed?.key === key ? changed.value : await globalConfig(key);
|
|
347
|
+
return orgIdentityStatus({
|
|
348
|
+
SWARM_ORG_NAME: await read("SWARM_ORG_NAME"),
|
|
349
|
+
SWARM_ORG_WEBSITE: await read("SWARM_ORG_WEBSITE")
|
|
350
|
+
});
|
|
351
|
+
}
|
|
352
|
+
async function storedListing() {
|
|
353
|
+
return readTelemetryRanking(await globalConfig(TELEMETRY_RANKING_KEY));
|
|
354
|
+
}
|
|
355
|
+
async function rankingEnabled() {
|
|
356
|
+
const raw = await globalConfig(PUBLIC_RANKING_ENABLED_KEY);
|
|
357
|
+
return isEnvFlagEnabled(PUBLIC_RANKING_ENABLED_KEY, false, {
|
|
358
|
+
[PUBLIC_RANKING_ENABLED_KEY]: raw
|
|
359
|
+
});
|
|
360
|
+
}
|
|
361
|
+
async function telemetryReady() {
|
|
362
|
+
return isTelemetryEnabled() && Boolean(await globalConfig("telemetry_installation_id"));
|
|
363
|
+
}
|
|
364
|
+
async function verifyUrl(domain) {
|
|
365
|
+
const params = new URLSearchParams({ domain });
|
|
366
|
+
return `${await telemetryProxyEndpoint("/v1/ranking/verify")}?${params.toString()}`;
|
|
367
|
+
}
|
|
368
|
+
function withoutClaim(listing) {
|
|
369
|
+
const { claim: _claim, ...rest } = listing;
|
|
370
|
+
return rest;
|
|
371
|
+
}
|
|
372
|
+
async function setEnabled(enabled) {
|
|
373
|
+
await upsertSwarmConfig2({
|
|
374
|
+
scope: "global",
|
|
375
|
+
key: PUBLIC_RANKING_ENABLED_KEY,
|
|
376
|
+
value: String(enabled)
|
|
377
|
+
});
|
|
378
|
+
}
|
|
379
|
+
function emitOptedIn(listing) {
|
|
380
|
+
telemetry.ranking("opted_in", { listing: JSON.stringify(withoutClaim(listing)) }, { orgName: listing.name, orgWebsite: listing.domain });
|
|
381
|
+
}
|
|
382
|
+
function emitOptedOut(domain) {
|
|
383
|
+
telemetry.ranking("opted_out", { domain });
|
|
384
|
+
}
|
|
385
|
+
async function buildRankingState() {
|
|
386
|
+
const [identity, listing, enabled, telemetryOn] = await Promise.all([
|
|
387
|
+
currentIdentity(),
|
|
388
|
+
storedListing(),
|
|
389
|
+
rankingEnabled(),
|
|
390
|
+
telemetryReady()
|
|
391
|
+
]);
|
|
392
|
+
const listingMatchesDomain = Boolean(listing && listing.domain === identity.website);
|
|
393
|
+
const current = listingMatchesDomain ? listing : null;
|
|
394
|
+
return {
|
|
395
|
+
eligible: telemetryOn && identity.ok,
|
|
396
|
+
missing: identity.missing,
|
|
397
|
+
telemetryOn,
|
|
398
|
+
enabled: enabled && listingMatchesDomain,
|
|
399
|
+
name: identity.name,
|
|
400
|
+
domain: identity.website,
|
|
401
|
+
listing: listing ? withoutClaim(listing) : null,
|
|
402
|
+
listingMatchesDomain,
|
|
403
|
+
verifyUrl: current ? await verifyUrl(current.domain) : null
|
|
404
|
+
};
|
|
405
|
+
}
|
|
406
|
+
async function syncRankingAfterConfigChange(key, value) {
|
|
407
|
+
if (!RANKING_CONFIG_KEYS.has(key))
|
|
408
|
+
return;
|
|
409
|
+
const listing = await storedListing();
|
|
410
|
+
if (!listing)
|
|
411
|
+
return;
|
|
412
|
+
if (key === PUBLIC_RANKING_ENABLED_KEY) {
|
|
413
|
+
if (!isEnvFlagEnabled(key, false, { [key]: value ?? undefined })) {
|
|
414
|
+
emitOptedOut(listing.domain);
|
|
415
|
+
}
|
|
416
|
+
return;
|
|
417
|
+
}
|
|
418
|
+
if (!await rankingEnabled())
|
|
419
|
+
return;
|
|
420
|
+
const identity = await currentIdentity({ key, value });
|
|
421
|
+
let rebuilt = null;
|
|
422
|
+
if (identity.ok && identity.website === listing.domain) {
|
|
423
|
+
if (identity.name === listing.name)
|
|
424
|
+
return;
|
|
425
|
+
try {
|
|
426
|
+
rebuilt = buildListing(identity, listing);
|
|
427
|
+
} catch {}
|
|
428
|
+
}
|
|
429
|
+
if (!rebuilt) {
|
|
430
|
+
await setEnabled(false);
|
|
431
|
+
emitOptedOut(listing.domain);
|
|
432
|
+
return;
|
|
433
|
+
}
|
|
434
|
+
await upsertSwarmConfig2({
|
|
435
|
+
scope: "global",
|
|
436
|
+
key: TELEMETRY_RANKING_KEY,
|
|
437
|
+
value: JSON.stringify(rebuilt)
|
|
438
|
+
});
|
|
439
|
+
emitOptedIn(rebuilt);
|
|
440
|
+
}
|
|
441
|
+
function conflict(res, body) {
|
|
442
|
+
res.writeHead(409, { "Content-Type": "application/json" });
|
|
443
|
+
res.end(JSON.stringify(body));
|
|
444
|
+
}
|
|
445
|
+
async function handleRanking(req, res, pathSegments, queryParams) {
|
|
446
|
+
if (getRanking.match(req.method, pathSegments)) {
|
|
447
|
+
const parsed = await getRanking.parse(req, res, pathSegments, queryParams);
|
|
448
|
+
if (!parsed)
|
|
449
|
+
return true;
|
|
450
|
+
if (!await ensureConfigAdmin(req, res, "config.write.any"))
|
|
451
|
+
return true;
|
|
452
|
+
getRanking.respond(res, 200, await buildRankingState());
|
|
453
|
+
return true;
|
|
454
|
+
}
|
|
455
|
+
if (optIn.match(req.method, pathSegments)) {
|
|
456
|
+
const parsed = await optIn.parse(req, res, pathSegments, queryParams);
|
|
457
|
+
if (!parsed)
|
|
458
|
+
return true;
|
|
459
|
+
if (!await ensureConfigAdmin(req, res, "config.write.any"))
|
|
460
|
+
return true;
|
|
461
|
+
if (!await telemetryReady()) {
|
|
462
|
+
conflict(res, {
|
|
463
|
+
error: "telemetry_off",
|
|
464
|
+
message: "Turn telemetry on first: the ranking counts tokens from telemetry."
|
|
465
|
+
});
|
|
466
|
+
return true;
|
|
467
|
+
}
|
|
468
|
+
const identity = await currentIdentity();
|
|
469
|
+
if (!identity.ok || !identity.website) {
|
|
470
|
+
conflict(res, {
|
|
471
|
+
error: "org_identity_missing",
|
|
472
|
+
message: "Set the organization name and website first",
|
|
473
|
+
missing: identity.missing
|
|
474
|
+
});
|
|
475
|
+
return true;
|
|
476
|
+
}
|
|
477
|
+
const db = getDbClient2();
|
|
478
|
+
const built = await db.transaction(async () => {
|
|
479
|
+
let listing;
|
|
480
|
+
try {
|
|
481
|
+
listing = buildListing(identity, parsed.body);
|
|
482
|
+
} catch (error) {
|
|
483
|
+
return { ok: false, error };
|
|
484
|
+
}
|
|
485
|
+
await upsertSwarmConfig2({
|
|
486
|
+
scope: "global",
|
|
487
|
+
key: TELEMETRY_RANKING_KEY,
|
|
488
|
+
value: JSON.stringify(listing)
|
|
489
|
+
});
|
|
490
|
+
await setEnabled(true);
|
|
491
|
+
db.afterCommit(() => emitOptedIn(listing));
|
|
492
|
+
return { ok: true, listing };
|
|
493
|
+
});
|
|
494
|
+
if (!built.ok) {
|
|
495
|
+
const issue = built.error instanceof ZodError ? built.error.issues[0] : undefined;
|
|
496
|
+
res.writeHead(400, { "Content-Type": "application/json" });
|
|
497
|
+
res.end(JSON.stringify({
|
|
498
|
+
error: issue ? `Invalid ${issue.path.join(".") || "listing"}: ${issue.message}` : "Invalid listing"
|
|
499
|
+
}));
|
|
500
|
+
return true;
|
|
501
|
+
}
|
|
502
|
+
const { listing } = built;
|
|
503
|
+
scheduleIntegrationsReload2();
|
|
504
|
+
optIn.respond(res, 200, {
|
|
505
|
+
domain: listing.domain,
|
|
506
|
+
listing,
|
|
507
|
+
verifyUrl: await verifyUrl(listing.domain)
|
|
508
|
+
});
|
|
509
|
+
return true;
|
|
510
|
+
}
|
|
511
|
+
if (optOut.match(req.method, pathSegments)) {
|
|
512
|
+
const parsed = await optOut.parse(req, res, pathSegments, queryParams);
|
|
513
|
+
if (!parsed)
|
|
514
|
+
return true;
|
|
515
|
+
if (!await ensureConfigAdmin(req, res, "config.write.any"))
|
|
516
|
+
return true;
|
|
517
|
+
const listing = await storedListing();
|
|
518
|
+
await setEnabled(false);
|
|
519
|
+
if (listing)
|
|
520
|
+
emitOptedOut(listing.domain);
|
|
521
|
+
scheduleIntegrationsReload2();
|
|
522
|
+
optOut.respond(res, 200, { enabled: false });
|
|
523
|
+
return true;
|
|
524
|
+
}
|
|
525
|
+
return false;
|
|
526
|
+
}
|
|
527
|
+
var ListingSchema, RankingStateSchema, OptInResponseSchema, OptOutResponseSchema, getRanking, optIn, optOut, RANKING_CONFIG_KEYS;
|
|
528
|
+
var init_ranking = __esm(() => {
|
|
529
|
+
init_zod();
|
|
530
|
+
init_db4();
|
|
531
|
+
init_telemetry_ranking();
|
|
532
|
+
init_telemetry();
|
|
533
|
+
init_env_flag();
|
|
534
|
+
init_org_identity();
|
|
535
|
+
init_config();
|
|
536
|
+
init_core();
|
|
537
|
+
init_global_config();
|
|
538
|
+
init_route_def();
|
|
539
|
+
init_used_by();
|
|
540
|
+
ListingSchema = object2({
|
|
541
|
+
v: literal2(1),
|
|
542
|
+
name: string2(),
|
|
543
|
+
domain: string2(),
|
|
544
|
+
category: _enum2(RANKING_CATEGORIES),
|
|
545
|
+
subcategory: string2().nullable(),
|
|
546
|
+
description: string2().nullable(),
|
|
547
|
+
sourceCodeUrl: string2().nullable(),
|
|
548
|
+
updatedAt: string2()
|
|
549
|
+
});
|
|
550
|
+
RankingStateSchema = object2({
|
|
551
|
+
eligible: boolean(),
|
|
552
|
+
missing: array2(_enum2(ORG_IDENTITY_KEYS)),
|
|
553
|
+
telemetryOn: boolean(),
|
|
554
|
+
enabled: boolean(),
|
|
555
|
+
name: string2().nullable(),
|
|
556
|
+
domain: string2().nullable(),
|
|
557
|
+
listing: ListingSchema.nullable(),
|
|
558
|
+
listingMatchesDomain: boolean(),
|
|
559
|
+
verifyUrl: string2().nullable()
|
|
560
|
+
});
|
|
561
|
+
OptInResponseSchema = object2({
|
|
562
|
+
domain: string2(),
|
|
563
|
+
listing: ListingSchema,
|
|
564
|
+
verifyUrl: string2()
|
|
565
|
+
});
|
|
566
|
+
OptOutResponseSchema = object2({
|
|
567
|
+
enabled: literal2(false)
|
|
568
|
+
});
|
|
569
|
+
getRanking = route({
|
|
570
|
+
method: "get",
|
|
571
|
+
path: "/api/ranking",
|
|
572
|
+
pattern: ["api", "ranking"],
|
|
573
|
+
summary: "Public ranking state",
|
|
574
|
+
description: "Whether this install can join the public agent-swarm.dev ranking (telemetry on, organization name and website set), whether it is opted in, and its stored listing. Only a config admin can read it.",
|
|
575
|
+
tags: ["Telemetry"],
|
|
576
|
+
responses: {
|
|
577
|
+
200: { description: "Ranking state", schema: RankingStateSchema },
|
|
578
|
+
401: { description: "Unauthorized" },
|
|
579
|
+
403: { description: "Only a config admin can read the ranking state" }
|
|
580
|
+
},
|
|
581
|
+
rbac: { permission: "config.write.any" }
|
|
582
|
+
});
|
|
583
|
+
optIn = route({
|
|
584
|
+
method: "post",
|
|
585
|
+
path: "/api/ranking/opt-in",
|
|
586
|
+
pattern: ["api", "ranking", "opt-in"],
|
|
587
|
+
summary: "Opt this install into the public ranking",
|
|
588
|
+
description: "Builds the telemetry_ranking listing from the organization name and website plus the chosen category, stores it, turns PUBLIC_RANKING_ENABLED on and sends ranking.opted_in. That is the whole opt-in: the install shows on agent-swarm.dev/ranking at the next hourly refresh.",
|
|
589
|
+
tags: ["Telemetry"],
|
|
590
|
+
body: rankingFormSchema,
|
|
591
|
+
responses: {
|
|
592
|
+
200: { description: "Opted in", schema: OptInResponseSchema },
|
|
593
|
+
400: { description: "A listing field is invalid" },
|
|
594
|
+
401: { description: "Unauthorized" },
|
|
595
|
+
403: { description: "Only a config admin can opt in" },
|
|
596
|
+
409: {
|
|
597
|
+
description: "telemetry_off: telemetry is off or the install has no ID. org_identity_missing: the organization name or website is not set (`missing` lists which)."
|
|
598
|
+
}
|
|
599
|
+
},
|
|
600
|
+
rbac: { permission: "config.write.any" }
|
|
601
|
+
});
|
|
602
|
+
optOut = route({
|
|
603
|
+
method: "post",
|
|
604
|
+
path: "/api/ranking/opt-out",
|
|
605
|
+
pattern: ["api", "ranking", "opt-out"],
|
|
606
|
+
summary: "Leave the public ranking",
|
|
607
|
+
description: "Turns PUBLIC_RANKING_ENABLED off and sends ranking.opted_out, so workers stop sending ranking.usage. The install leaves agent-swarm.dev/ranking at the next hourly refresh.",
|
|
608
|
+
tags: ["Telemetry"],
|
|
609
|
+
responses: {
|
|
610
|
+
200: { description: "Opted out", schema: OptOutResponseSchema },
|
|
611
|
+
401: { description: "Unauthorized" },
|
|
612
|
+
403: { description: "Only a config admin can opt out" }
|
|
613
|
+
},
|
|
614
|
+
rbac: { permission: "config.write.any" }
|
|
615
|
+
});
|
|
616
|
+
RANKING_CONFIG_KEYS = new Set([...ORG_IDENTITY_KEYS, PUBLIC_RANKING_ENABLED_KEY]);
|
|
617
|
+
});
|
|
618
|
+
|
|
619
|
+
// src/http/config.ts
|
|
620
|
+
function stripApiOnlyKeys(configs) {
|
|
621
|
+
return configs.filter((config) => !isApiOnlyConfigKey(config.key) && !isInternalConfigKey(config.key));
|
|
622
|
+
}
|
|
623
|
+
function singleHeader(req, name) {
|
|
624
|
+
const raw = req.headers[name];
|
|
625
|
+
return Array.isArray(raw) ? raw[0] : raw;
|
|
626
|
+
}
|
|
627
|
+
function readsRepoSecrets(auth, agent) {
|
|
628
|
+
if (auth?.kind !== "agent" || !auth.runtimeId)
|
|
629
|
+
return true;
|
|
630
|
+
return runtimeReadsRepoSecrets({ id: auth.agentId, isLead: agent?.isLead });
|
|
631
|
+
}
|
|
632
|
+
async function requestSecretReadScope(req, resolvedScope) {
|
|
633
|
+
const principal = await requestPrincipal(req, undefined);
|
|
634
|
+
if (!principal || principal.kind === "operator")
|
|
635
|
+
return "all";
|
|
636
|
+
if (principal.kind === "guest")
|
|
637
|
+
return "none";
|
|
638
|
+
if (principal.kind === "agent") {
|
|
639
|
+
if (can({
|
|
640
|
+
principal,
|
|
641
|
+
verb: "config.read.secrets",
|
|
642
|
+
resource: { kind: "none" },
|
|
643
|
+
source: "http"
|
|
644
|
+
}).allow)
|
|
645
|
+
return "all";
|
|
646
|
+
const auth = getRequestAuth(req);
|
|
647
|
+
if (auth?.kind === "agent" && auth.tokenKind === "task" || resolvedScope?.agentId !== principal.agentId)
|
|
648
|
+
return "none";
|
|
649
|
+
return "self";
|
|
650
|
+
}
|
|
651
|
+
if (!isRbacEnabled())
|
|
652
|
+
return "all";
|
|
653
|
+
const grant = await getUserGrant2(principal.userId);
|
|
654
|
+
return grant.grantsAll || grant.verbs.has("config.read.secrets") ? "all" : "none";
|
|
655
|
+
}
|
|
656
|
+
async function resolveSecretsRead(req, includeSecrets, resolvedScope) {
|
|
657
|
+
const scope = await requestSecretReadScope(req, resolvedScope);
|
|
658
|
+
const auth = getRequestAuth(req);
|
|
659
|
+
return {
|
|
660
|
+
effectiveIncludeSecrets: includeSecrets && scope !== "none",
|
|
661
|
+
includeRepoSecrets: !(auth?.kind === "agent" && auth.tokenKind !== "task" && scope !== "all"),
|
|
662
|
+
secretsNote: includeSecrets && scope === "none" ? SECRETS_FORCE_MASK_NOTE : ""
|
|
663
|
+
};
|
|
664
|
+
}
|
|
665
|
+
async function scriptRunHeldConfigIds(req) {
|
|
666
|
+
const auth = getRequestAuth(req);
|
|
667
|
+
if (auth?.kind !== "agent" || auth.tokenKind !== "agent")
|
|
668
|
+
return;
|
|
669
|
+
if (!await isScriptRunToken(auth.tokenId))
|
|
670
|
+
return;
|
|
671
|
+
const held = stripApiOnlyKeys(await getResolvedConfig2(auth.agentId, undefined, { includeRepoSecrets: false }));
|
|
672
|
+
return new Set(held.map((config) => config.id));
|
|
673
|
+
}
|
|
674
|
+
async function maskConfigRead(req, configs, includeSecrets) {
|
|
675
|
+
const { effectiveIncludeSecrets, secretsNote } = await resolveSecretsRead(req, includeSecrets);
|
|
676
|
+
const held = includeSecrets && !effectiveIncludeSecrets ? await scriptRunHeldConfigIds(req) : undefined;
|
|
677
|
+
const reveal = (config) => effectiveIncludeSecrets || !!held?.has(config.id);
|
|
678
|
+
const result = configs.map((config) => config.isSecret && !reveal(config) ? maskSecrets2([config])[0] : config);
|
|
679
|
+
for (const config of result) {
|
|
680
|
+
if (config.isSecret && config.value && reveal(config)) {
|
|
681
|
+
registerVolatileSecret(config.value, `config:${config.key}`);
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
const anyMasked = result.some((config) => config.isSecret && !reveal(config));
|
|
685
|
+
return { result, secretsNote: held && !anyMasked ? "" : secretsNote };
|
|
686
|
+
}
|
|
687
|
+
async function ensureConfigAdmin(req, res, verb) {
|
|
688
|
+
return ensureHttpPermission(req, res, verb, verb === "config.write.any" ? "Writing swarm config requires the lead agent" : "Deleting swarm config requires the lead agent");
|
|
689
|
+
}
|
|
690
|
+
async function ensureHumanOnlyConfigWrite(req, res, key) {
|
|
691
|
+
if (!isHumanOnlyConfigKey(key))
|
|
692
|
+
return true;
|
|
693
|
+
const auth = getRequestAuth(req);
|
|
694
|
+
if (auth?.page) {
|
|
695
|
+
jsonError(res, humanOnlyConfigKeyPageError(key), 403);
|
|
696
|
+
return false;
|
|
697
|
+
}
|
|
698
|
+
const userId = authUserId(auth);
|
|
699
|
+
if (userId && (!isRbacEnabled() || (await getUserGrant2(userId)).grantsAll))
|
|
700
|
+
return true;
|
|
701
|
+
jsonError(res, humanOnlyConfigKeyError(key), 403);
|
|
702
|
+
return false;
|
|
703
|
+
}
|
|
704
|
+
async function runConfigWriteSideEffects(scope, key, value) {
|
|
705
|
+
if (scope !== "global")
|
|
706
|
+
return;
|
|
707
|
+
if (key === "SWARM_ORG_WEBSITE")
|
|
708
|
+
await fillOrgLogoFromWebsite(value);
|
|
709
|
+
await syncRankingAfterConfigChange(key, value);
|
|
710
|
+
scheduleIntegrationsReload2();
|
|
711
|
+
}
|
|
712
|
+
async function ensureHttpPermission(req, res, verb, forbiddenMessage, callerAgentId) {
|
|
713
|
+
const principal = await requestPrincipal(req, callerAgentId ?? singleHeader(req, "x-agent-id"), {
|
|
714
|
+
unauthenticatedFallback: "anonymous-agent"
|
|
715
|
+
});
|
|
716
|
+
if (principal.kind === "operator" || principal.kind === "user")
|
|
717
|
+
return true;
|
|
718
|
+
if (principal.kind === "guest") {
|
|
719
|
+
jsonError(res, "Forbidden", 403);
|
|
720
|
+
return false;
|
|
721
|
+
}
|
|
722
|
+
const decision = can({
|
|
723
|
+
principal,
|
|
724
|
+
verb,
|
|
725
|
+
resource: { kind: "none" },
|
|
726
|
+
source: "http"
|
|
727
|
+
});
|
|
728
|
+
if (!decision.allow) {
|
|
729
|
+
jsonError(res, forbiddenMessage, 403);
|
|
730
|
+
return false;
|
|
731
|
+
}
|
|
732
|
+
return true;
|
|
733
|
+
}
|
|
734
|
+
async function handleConfig(req, res, pathSegments, queryParams) {
|
|
735
|
+
if (getRequestAuth(req)?.kind === "agent") {
|
|
736
|
+
const duplicate = duplicateGuardedQueryKey(queryParams);
|
|
737
|
+
if (duplicate) {
|
|
738
|
+
jsonError(res, `Duplicate query parameter: ${duplicate}`, 400);
|
|
739
|
+
return true;
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
if (getResolvedConfigRoute.match(req.method, pathSegments)) {
|
|
743
|
+
const parsed = await getResolvedConfigRoute.parse(req, res, pathSegments, queryParams);
|
|
744
|
+
if (!parsed)
|
|
745
|
+
return true;
|
|
746
|
+
const includeSecrets = parsed.query.includeSecrets === "true";
|
|
747
|
+
const key = parsed.query.key;
|
|
748
|
+
const auth = getRequestAuth(req);
|
|
749
|
+
const resolvedScope = {
|
|
750
|
+
agentId: parsed.query.agentId || (auth?.kind === "agent" && auth.tokenKind !== "task" ? auth.agentId : undefined),
|
|
751
|
+
repoId: parsed.query.repoId || undefined
|
|
752
|
+
};
|
|
753
|
+
const { effectiveIncludeSecrets, includeRepoSecrets, secretsNote } = await resolveSecretsRead(req, includeSecrets, resolvedScope);
|
|
754
|
+
const configs = stripApiOnlyKeys(await getResolvedConfig2(resolvedScope.agentId, resolvedScope.repoId, { includeRepoSecrets })).filter((c) => !key || c.key === key);
|
|
755
|
+
const result = effectiveIncludeSecrets ? configs : maskSecrets2(configs);
|
|
756
|
+
if (effectiveIncludeSecrets) {
|
|
757
|
+
for (const c of result) {
|
|
758
|
+
if (c.isSecret && c.value) {
|
|
759
|
+
registerVolatileSecret(c.value, `config:${c.key}`);
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
getResolvedConfigRoute.respond(res, 200, {
|
|
764
|
+
configs: result,
|
|
765
|
+
...secretsNote ? { message: `Found ${result.length} config(s).${secretsNote}` } : {}
|
|
766
|
+
});
|
|
767
|
+
return true;
|
|
768
|
+
}
|
|
769
|
+
if (envPresence.match(req.method, pathSegments)) {
|
|
770
|
+
const parsed = await envPresence.parse(req, res, pathSegments, queryParams);
|
|
771
|
+
if (!parsed)
|
|
772
|
+
return true;
|
|
773
|
+
const keys = parsed.query.keys.split(",").map((k) => k.trim()).filter(Boolean);
|
|
774
|
+
if (keys.length > MAX_ENV_PRESENCE_KEYS) {
|
|
775
|
+
jsonError(res, `Too many keys (max ${MAX_ENV_PRESENCE_KEYS})`, 400);
|
|
776
|
+
return true;
|
|
777
|
+
}
|
|
778
|
+
const presence = {};
|
|
779
|
+
for (const key of keys) {
|
|
780
|
+
const value = key === "SWARM_ORG_NAME" ? process.env[key]?.trim() : process.env[key];
|
|
781
|
+
presence[key] = value !== undefined && (isSlackIconConfigKey(key) || value !== "");
|
|
782
|
+
}
|
|
783
|
+
envPresence.respond(res, 200, { presence });
|
|
784
|
+
return true;
|
|
785
|
+
}
|
|
786
|
+
if (reloadConfigRoute.match(req.method, pathSegments)) {
|
|
787
|
+
try {
|
|
788
|
+
const result = await reloadGlobalConfigsAndIntegrations2();
|
|
789
|
+
console.log(`[reload-config] Loaded ${result.configsLoaded} config(s), re-initialized: ${result.integrationsReinitialized.join(", ") || "none"}`);
|
|
790
|
+
reloadConfigRoute.respond(res, 200, { success: true, ...result });
|
|
791
|
+
} catch (e) {
|
|
792
|
+
const message = e instanceof Error ? e.message : String(e);
|
|
793
|
+
console.error("[reload-config] Failed:", message);
|
|
794
|
+
jsonError(res, `Failed to reload config: ${message}`, 500);
|
|
795
|
+
}
|
|
796
|
+
return true;
|
|
797
|
+
}
|
|
798
|
+
if (getConfigById.match(req.method, pathSegments)) {
|
|
799
|
+
const parsed = await getConfigById.parse(req, res, pathSegments, queryParams);
|
|
800
|
+
if (!parsed)
|
|
801
|
+
return true;
|
|
802
|
+
const includeSecrets = parsed.query.includeSecrets === "true";
|
|
803
|
+
const config = await getSwarmConfigById2(parsed.params.id);
|
|
804
|
+
if (!config || isInternalConfigKey(config.key)) {
|
|
805
|
+
jsonError(res, "Config not found", 404);
|
|
806
|
+
return true;
|
|
807
|
+
}
|
|
808
|
+
const { result, secretsNote } = await maskConfigRead(req, [config], includeSecrets);
|
|
809
|
+
getConfigById.respond(res, 200, {
|
|
810
|
+
...result[0],
|
|
811
|
+
...secretsNote ? { message: `Found 1 config(s).${secretsNote}` } : {}
|
|
812
|
+
});
|
|
813
|
+
return true;
|
|
814
|
+
}
|
|
815
|
+
if (listConfig.match(req.method, pathSegments)) {
|
|
816
|
+
const parsed = await listConfig.parse(req, res, pathSegments, queryParams);
|
|
817
|
+
if (!parsed)
|
|
818
|
+
return true;
|
|
819
|
+
const includeSecrets = parsed.query.includeSecrets === "true";
|
|
820
|
+
const configs = stripApiOnlyKeys(await getSwarmConfigs2({
|
|
821
|
+
scope: parsed.query.scope || undefined,
|
|
822
|
+
scopeId: parsed.query.scopeId || undefined,
|
|
823
|
+
key: parsed.query.key
|
|
824
|
+
}));
|
|
825
|
+
const { result: listResult, secretsNote } = await maskConfigRead(req, configs, includeSecrets);
|
|
826
|
+
listConfig.respond(res, 200, {
|
|
827
|
+
configs: listResult,
|
|
828
|
+
...secretsNote ? { message: `Found ${listResult.length} config(s).${secretsNote}` } : {}
|
|
829
|
+
});
|
|
830
|
+
return true;
|
|
831
|
+
}
|
|
832
|
+
if (upsertConfig.match(req.method, pathSegments)) {
|
|
833
|
+
const parsed = await upsertConfig.parse(req, res, pathSegments, queryParams);
|
|
834
|
+
if (!parsed)
|
|
835
|
+
return true;
|
|
836
|
+
if (!await ensureConfigAdmin(req, res, "config.write.any"))
|
|
837
|
+
return true;
|
|
838
|
+
const { scope, scopeId, key, value, isSecret, envPath, description, exportToEnv } = parsed.body;
|
|
839
|
+
if (!await ensureHumanOnlyConfigWrite(req, res, key))
|
|
840
|
+
return true;
|
|
841
|
+
const validationError = validateConfigEntry({ scope, scopeId, key, value, exportToEnv });
|
|
842
|
+
if (validationError) {
|
|
843
|
+
jsonError(res, validationError, 400);
|
|
844
|
+
return true;
|
|
845
|
+
}
|
|
846
|
+
try {
|
|
847
|
+
const includeSecrets = queryParams.get("includeSecrets") === "true";
|
|
848
|
+
const config = await upsertSwarmConfigWithPolicyMirror({
|
|
849
|
+
scope,
|
|
850
|
+
scopeId: scopeId || null,
|
|
851
|
+
key,
|
|
852
|
+
value: String(value),
|
|
853
|
+
isSecret: isSecret || false,
|
|
854
|
+
envPath: envPath || null,
|
|
855
|
+
description: description || null,
|
|
856
|
+
exportToEnv
|
|
857
|
+
});
|
|
858
|
+
await runConfigWriteSideEffects(scope, key, String(value));
|
|
859
|
+
const result = includeSecrets || !config.isSecret ? config : maskSecrets2([config])[0];
|
|
860
|
+
upsertConfig.respond(res, 200, result);
|
|
861
|
+
} catch (error) {
|
|
862
|
+
if (modelProfileRefError(error) === "missing") {
|
|
863
|
+
jsonError(res, `Unknown model profile "${String(value)}"`, 400);
|
|
864
|
+
return true;
|
|
865
|
+
}
|
|
866
|
+
jsonError(res, "Failed to upsert config", 500);
|
|
867
|
+
}
|
|
868
|
+
return true;
|
|
869
|
+
}
|
|
870
|
+
if (deleteConfig.match(req.method, pathSegments)) {
|
|
871
|
+
const parsed = await deleteConfig.parse(req, res, pathSegments, queryParams);
|
|
872
|
+
if (!parsed)
|
|
873
|
+
return true;
|
|
874
|
+
if (!await ensureConfigAdmin(req, res, "config.delete.any"))
|
|
875
|
+
return true;
|
|
876
|
+
const existing = await getSwarmConfigLookupById2(parsed.params.id);
|
|
877
|
+
if (!existing) {
|
|
878
|
+
jsonError(res, "Config not found", 404);
|
|
879
|
+
return true;
|
|
880
|
+
}
|
|
881
|
+
if (isInternalConfigKey(existing.key)) {
|
|
882
|
+
jsonError(res, internalConfigKeyError(existing.key).message, 400);
|
|
883
|
+
return true;
|
|
884
|
+
}
|
|
885
|
+
if (!await ensureHumanOnlyConfigWrite(req, res, existing.key))
|
|
886
|
+
return true;
|
|
887
|
+
const deleted = await deleteSwarmConfig2(parsed.params.id);
|
|
888
|
+
if (!deleted) {
|
|
889
|
+
jsonError(res, "Config not found", 404);
|
|
890
|
+
return true;
|
|
891
|
+
}
|
|
892
|
+
if (existing.scope === "global") {
|
|
893
|
+
await syncRankingAfterConfigChange(existing.key, null);
|
|
894
|
+
scheduleIntegrationsReload2();
|
|
895
|
+
}
|
|
896
|
+
if (existing.scope === "agent" && existing.scopeId && existing.key === AGENT_MAX_TASKS_CONFIG_KEY) {
|
|
897
|
+
await resetAgentMaxTasksMirror(existing.scopeId);
|
|
898
|
+
}
|
|
899
|
+
deleteConfig.respond(res, 200, { success: true });
|
|
900
|
+
return true;
|
|
901
|
+
}
|
|
902
|
+
return false;
|
|
903
|
+
}
|
|
904
|
+
var MAX_ENV_PRESENCE_KEYS = 200, SECRETS_FORCE_MASK_NOTE = " (secret values masked: this token cannot read secrets in this scope)", getResolvedConfigRoute, envPresence, reloadConfigRoute, getConfigById, listConfig, upsertConfig, deleteConfig;
|
|
905
|
+
var init_config = __esm(() => {
|
|
906
|
+
init_zod();
|
|
907
|
+
init_db4();
|
|
908
|
+
init_model_profiles();
|
|
909
|
+
init_model_profile_check();
|
|
910
|
+
init_multi_runtime();
|
|
911
|
+
init_org_profile();
|
|
912
|
+
init_rbac_roles();
|
|
913
|
+
init_swarm_config_guard();
|
|
914
|
+
init_users();
|
|
915
|
+
init_rbac();
|
|
916
|
+
init_reaction_shortcode();
|
|
917
|
+
init_types5();
|
|
918
|
+
init_request_auth_context();
|
|
919
|
+
init_secret_scrubber();
|
|
920
|
+
init_core();
|
|
921
|
+
init_ranking();
|
|
922
|
+
init_request_principal();
|
|
923
|
+
init_route_def();
|
|
924
|
+
init_utils2();
|
|
925
|
+
getResolvedConfigRoute = route({
|
|
926
|
+
method: "get",
|
|
927
|
+
path: "/api/config/resolved",
|
|
928
|
+
pattern: ["api", "config", "resolved"],
|
|
929
|
+
summary: "Get resolved config (merged global + agent + repo scopes)",
|
|
930
|
+
tags: ["Config"],
|
|
931
|
+
query: object2({
|
|
932
|
+
agentId: string2().optional(),
|
|
933
|
+
repoId: string2().optional(),
|
|
934
|
+
key: string2().min(1).optional().describe("Return only the entry with this exact key. Omit to return every resolved entry."),
|
|
935
|
+
includeSecrets: _enum2(["true", "false"]).optional()
|
|
936
|
+
}),
|
|
937
|
+
responses: {
|
|
938
|
+
200: {
|
|
939
|
+
description: "Resolved config entries",
|
|
940
|
+
schema: object2({
|
|
941
|
+
configs: array2(SwarmConfigSchema),
|
|
942
|
+
message: string2().optional()
|
|
943
|
+
})
|
|
944
|
+
}
|
|
945
|
+
}
|
|
946
|
+
});
|
|
947
|
+
envPresence = route({
|
|
948
|
+
method: "get",
|
|
949
|
+
path: "/api/config/env-presence",
|
|
950
|
+
pattern: ["api", "config", "env-presence"],
|
|
951
|
+
summary: "Check which of the given env var keys are currently set in process.env (presence only, no values)",
|
|
952
|
+
tags: ["Config"],
|
|
953
|
+
query: object2({
|
|
954
|
+
keys: string2().min(1)
|
|
955
|
+
}),
|
|
956
|
+
responses: {
|
|
957
|
+
200: {
|
|
958
|
+
description: "Map of key -> boolean (true iff set in process.env)",
|
|
959
|
+
schema: object2({ presence: record2(string2(), boolean()) })
|
|
960
|
+
},
|
|
961
|
+
400: { description: "Validation error" }
|
|
962
|
+
}
|
|
963
|
+
});
|
|
964
|
+
reloadConfigRoute = route({
|
|
965
|
+
method: "post",
|
|
966
|
+
path: "/api/config/reload",
|
|
967
|
+
pattern: ["api", "config", "reload"],
|
|
968
|
+
summary: "Reload global swarm_config into process.env (override=true) and re-init integrations (Slack, GitHub, Linear, AgentMail)",
|
|
969
|
+
tags: ["Config"],
|
|
970
|
+
body: object2({}).optional(),
|
|
971
|
+
responses: {
|
|
972
|
+
200: {
|
|
973
|
+
description: "Reload result",
|
|
974
|
+
schema: object2({
|
|
975
|
+
success: literal2(true),
|
|
976
|
+
configsLoaded: number2(),
|
|
977
|
+
keysUpdated: array2(string2()),
|
|
978
|
+
integrationsReinitialized: array2(string2())
|
|
979
|
+
})
|
|
980
|
+
},
|
|
981
|
+
500: { description: "Reload failed" }
|
|
982
|
+
}
|
|
983
|
+
});
|
|
984
|
+
getConfigById = route({
|
|
985
|
+
method: "get",
|
|
986
|
+
path: "/api/config/{id}",
|
|
987
|
+
pattern: ["api", "config", null],
|
|
988
|
+
summary: "Get a single config entry by ID",
|
|
989
|
+
tags: ["Config"],
|
|
990
|
+
params: object2({ id: string2() }),
|
|
991
|
+
query: object2({
|
|
992
|
+
includeSecrets: _enum2(["true", "false"]).optional()
|
|
993
|
+
}),
|
|
994
|
+
responses: {
|
|
995
|
+
200: {
|
|
996
|
+
description: "Config entry",
|
|
997
|
+
schema: SwarmConfigSchema.extend({ message: string2().optional() })
|
|
998
|
+
},
|
|
999
|
+
404: { description: "Config not found" }
|
|
1000
|
+
}
|
|
1001
|
+
});
|
|
1002
|
+
listConfig = route({
|
|
1003
|
+
method: "get",
|
|
1004
|
+
path: "/api/config",
|
|
1005
|
+
pattern: ["api", "config"],
|
|
1006
|
+
summary: "List config entries with optional filters",
|
|
1007
|
+
tags: ["Config"],
|
|
1008
|
+
query: object2({
|
|
1009
|
+
scope: string2().optional(),
|
|
1010
|
+
scopeId: string2().optional(),
|
|
1011
|
+
key: string2().min(1).optional().describe("Return only entries with this exact key. Omit to return every entry."),
|
|
1012
|
+
includeSecrets: _enum2(["true", "false"]).optional()
|
|
1013
|
+
}),
|
|
1014
|
+
responses: {
|
|
1015
|
+
200: {
|
|
1016
|
+
description: "List of config entries",
|
|
1017
|
+
schema: object2({
|
|
1018
|
+
configs: array2(SwarmConfigSchema),
|
|
1019
|
+
message: string2().optional()
|
|
1020
|
+
})
|
|
1021
|
+
}
|
|
1022
|
+
}
|
|
1023
|
+
});
|
|
1024
|
+
upsertConfig = route({
|
|
1025
|
+
method: "put",
|
|
1026
|
+
path: "/api/config",
|
|
1027
|
+
pattern: ["api", "config"],
|
|
1028
|
+
summary: "Create or update a config entry (reserved env-only keys are rejected). Global-scope writes auto-trigger an integrations reload (debounced ~250ms) so Slack/GitHub/Linear/Jira/AgentMail pick up new credentials without an explicit /api/config/reload call.",
|
|
1029
|
+
tags: ["Config"],
|
|
1030
|
+
rbac: { permission: "config.write.any" },
|
|
1031
|
+
body: object2({
|
|
1032
|
+
scope: _enum2(["global", "agent", "repo"]),
|
|
1033
|
+
scopeId: string2().nullish(),
|
|
1034
|
+
key: string2().min(1),
|
|
1035
|
+
value: unknown(),
|
|
1036
|
+
isSecret: boolean().optional(),
|
|
1037
|
+
envPath: string2().nullish(),
|
|
1038
|
+
description: string2().nullish(),
|
|
1039
|
+
exportToEnv: boolean().optional().describe("Export this row into agent process env (default true on create, false for a few server-side secrets; omitted on update keeps the stored flag). Rejected as true for keys only the API server reads.")
|
|
1040
|
+
}),
|
|
1041
|
+
responses: {
|
|
1042
|
+
200: { description: "Config entry upserted", schema: SwarmConfigSchema },
|
|
1043
|
+
400: { description: "Validation error" }
|
|
1044
|
+
}
|
|
1045
|
+
});
|
|
1046
|
+
deleteConfig = route({
|
|
1047
|
+
method: "delete",
|
|
1048
|
+
path: "/api/config/{id}",
|
|
1049
|
+
pattern: ["api", "config", null],
|
|
1050
|
+
summary: "Delete a config entry by ID (including legacy reserved rows for cleanup). Global-scope deletes auto-trigger an integrations reload.",
|
|
1051
|
+
tags: ["Config"],
|
|
1052
|
+
rbac: { permission: "config.delete.any" },
|
|
1053
|
+
params: object2({ id: string2() }),
|
|
1054
|
+
responses: {
|
|
1055
|
+
200: {
|
|
1056
|
+
description: "Config deleted",
|
|
1057
|
+
schema: object2({ success: literal2(true) })
|
|
1058
|
+
},
|
|
1059
|
+
404: { description: "Config not found" }
|
|
1060
|
+
}
|
|
1061
|
+
});
|
|
1062
|
+
});
|
|
1063
|
+
|
|
1064
|
+
// src/http/person-responder.ts
|
|
1065
|
+
async function approvalResponder(req, options) {
|
|
1066
|
+
const auth = getRequestAuth(req);
|
|
1067
|
+
const rawAgentId = req.headers["x-agent-id"];
|
|
1068
|
+
const headerAgentId = Array.isArray(rawAgentId) ? rawAgentId[0] : rawAgentId;
|
|
1069
|
+
const principal = await agentFirstPrincipal(req, headerAgentId);
|
|
1070
|
+
if (principal.kind !== "user" && principal.kind !== "agent" && auth?.page) {
|
|
1071
|
+
return {
|
|
1072
|
+
ok: false,
|
|
1073
|
+
message: options?.pageMessage ?? "A page session without a signed-in user cannot answer approval requests."
|
|
1074
|
+
};
|
|
1075
|
+
}
|
|
1076
|
+
const user = authUser(auth);
|
|
1077
|
+
const responder = principal.kind === "user" && user ? { kind: "user", user } : principal.kind === "operator" ? { kind: "operator" } : null;
|
|
1078
|
+
const verb = options?.verb ?? "approval.respond";
|
|
1079
|
+
const refused = {
|
|
1080
|
+
ok: false,
|
|
1081
|
+
message: options?.refusedMessage ?? AGENT_RESPONSE_REFUSED
|
|
1082
|
+
};
|
|
1083
|
+
const decision = can({ principal, verb, source: "http" });
|
|
1084
|
+
if (!decision.allow || !responder)
|
|
1085
|
+
return refused;
|
|
1086
|
+
if (responder.kind === "user" && isRbacEnabled()) {
|
|
1087
|
+
const grant = await getUserGrant2(responder.user.id);
|
|
1088
|
+
if (!grant.grantsAll && !grant.verbs.has(verb))
|
|
1089
|
+
return refused;
|
|
1090
|
+
}
|
|
1091
|
+
return { ok: true, responder };
|
|
1092
|
+
}
|
|
1093
|
+
function responderKey(responder) {
|
|
1094
|
+
return responder.kind === "user" ? responder.user.id : "operator";
|
|
1095
|
+
}
|
|
1096
|
+
async function userApprovalResponder(userId) {
|
|
1097
|
+
const refused = {
|
|
1098
|
+
ok: false,
|
|
1099
|
+
message: "You are not allowed to answer approval requests."
|
|
1100
|
+
};
|
|
1101
|
+
const user = await findUserById(userId);
|
|
1102
|
+
if (!user || user.status !== "active" || user.mergedIntoUserId)
|
|
1103
|
+
return refused;
|
|
1104
|
+
const verb = "approval.respond";
|
|
1105
|
+
if (!can({ principal: { kind: "user", userId }, verb, source: "http" }).allow)
|
|
1106
|
+
return refused;
|
|
1107
|
+
if (isRbacEnabled()) {
|
|
1108
|
+
const grant = await getUserGrant2(userId);
|
|
1109
|
+
if (!grant.grantsAll && !grant.verbs.has(verb))
|
|
1110
|
+
return refused;
|
|
1111
|
+
}
|
|
1112
|
+
return { ok: true, responder: { kind: "user", user } };
|
|
1113
|
+
}
|
|
1114
|
+
var AGENT_RESPONSE_REFUSED = "Agents cannot answer approval requests. A person must respond with a user token or the dashboard.";
|
|
1115
|
+
var init_person_responder = __esm(() => {
|
|
1116
|
+
init_rbac_roles();
|
|
1117
|
+
init_users();
|
|
1118
|
+
init_rbac();
|
|
1119
|
+
init_request_auth_context();
|
|
1120
|
+
init_request_principal();
|
|
1121
|
+
});
|
|
1122
|
+
|
|
1123
|
+
// src/http/approval-requests.ts
|
|
1124
|
+
async function toApprovalRequestResponse(request, options = {}) {
|
|
1125
|
+
const approvers = request.approvers;
|
|
1126
|
+
const approvals = request.approvals ?? null;
|
|
1127
|
+
const configState = options.withConfigState ? await readConfigStates(request.questions) : undefined;
|
|
1128
|
+
return {
|
|
1129
|
+
...request,
|
|
1130
|
+
...configState ? { configState } : {},
|
|
1131
|
+
questions: request.questions,
|
|
1132
|
+
approvers,
|
|
1133
|
+
responses: request.responses,
|
|
1134
|
+
approvals,
|
|
1135
|
+
approvalProgress: request.status === "pending" ? await approvalProgress(approvers, approvals ?? []) : null,
|
|
1136
|
+
notificationChannels: request.notificationChannels
|
|
1137
|
+
};
|
|
1138
|
+
}
|
|
1139
|
+
async function withApprovalProgress(rows, viewer) {
|
|
1140
|
+
const pendingIds = rows.filter((row) => row.status === "pending").map((row) => row.id);
|
|
1141
|
+
const state = new Map((await getPendingApprovalVoteState2(pendingIds)).map((entry) => [entry.id, entry]));
|
|
1142
|
+
return Promise.all(rows.map(async (row) => {
|
|
1143
|
+
const entry = state.get(row.id);
|
|
1144
|
+
return {
|
|
1145
|
+
...row,
|
|
1146
|
+
approvalProgress: entry ? await approvalProgress(entry.approvers, entry.approvals ?? []) : null,
|
|
1147
|
+
...entry && {
|
|
1148
|
+
viewerCanRespond: viewer !== null && isListedApprover(entry.approvers, viewer)
|
|
1149
|
+
}
|
|
1150
|
+
};
|
|
1151
|
+
}));
|
|
1152
|
+
}
|
|
1153
|
+
async function readConfigStates(questions) {
|
|
1154
|
+
const configQuestions = questions.filter(isConfigQuestion);
|
|
1155
|
+
if (configQuestions.length === 0)
|
|
1156
|
+
return;
|
|
1157
|
+
const entries = await Promise.all(configQuestions.map(async (q) => [q.id, await readConfigState(q.config)]));
|
|
1158
|
+
return Object.fromEntries(entries);
|
|
1159
|
+
}
|
|
1160
|
+
async function getWorkflowApprovalUnavailableReason(request) {
|
|
1161
|
+
if (!request.workflowRunId || !request.workflowRunStepId)
|
|
1162
|
+
return null;
|
|
1163
|
+
const run = await getWorkflowRun2(request.workflowRunId);
|
|
1164
|
+
if (!run)
|
|
1165
|
+
return "The workflow run no longer exists";
|
|
1166
|
+
if (run.status !== "running" && run.status !== "waiting") {
|
|
1167
|
+
return `The workflow run is ${run.status} and this approval is no longer actionable`;
|
|
1168
|
+
}
|
|
1169
|
+
const step = await getWorkflowRunStep2(request.workflowRunStepId);
|
|
1170
|
+
if (!step)
|
|
1171
|
+
return "The human-in-the-loop step no longer exists";
|
|
1172
|
+
if (step.runId !== run.id) {
|
|
1173
|
+
return "The human-in-the-loop step belongs to a different workflow run";
|
|
1174
|
+
}
|
|
1175
|
+
if (step.status !== "waiting") {
|
|
1176
|
+
return `The human-in-the-loop step is ${step.status} and this approval is no longer actionable`;
|
|
1177
|
+
}
|
|
1178
|
+
return null;
|
|
1179
|
+
}
|
|
1180
|
+
function hasRequiredResponse(question, response) {
|
|
1181
|
+
switch (question.type) {
|
|
1182
|
+
case "approval":
|
|
1183
|
+
return typeof response === "object" && response !== null && typeof response.approved === "boolean";
|
|
1184
|
+
case "text":
|
|
1185
|
+
return typeof response === "string" && response.trim().length > 0;
|
|
1186
|
+
case "single-select":
|
|
1187
|
+
return typeof response === "string" && response.length > 0 && (!question.options || question.options.some((option) => option.value === response));
|
|
1188
|
+
case "multi-select": {
|
|
1189
|
+
if (!Array.isArray(response))
|
|
1190
|
+
return false;
|
|
1191
|
+
const minimum = Math.max(1, question.minSelections ?? 0);
|
|
1192
|
+
if (response.length < minimum)
|
|
1193
|
+
return false;
|
|
1194
|
+
if (question.maxSelections !== undefined && response.length > question.maxSelections) {
|
|
1195
|
+
return false;
|
|
1196
|
+
}
|
|
1197
|
+
return response.every((value) => typeof value === "string" && (!question.options || question.options.some((option) => option.value === value)));
|
|
1198
|
+
}
|
|
1199
|
+
case "boolean":
|
|
1200
|
+
return typeof response === "boolean";
|
|
1201
|
+
case "config": {
|
|
1202
|
+
if (typeof response !== "object" || response === null)
|
|
1203
|
+
return false;
|
|
1204
|
+
const answer = response;
|
|
1205
|
+
if (answer.action === "keep")
|
|
1206
|
+
return true;
|
|
1207
|
+
return answer.action === "set" && typeof answer.value === "string" && answer.value.trim() !== "";
|
|
1208
|
+
}
|
|
1209
|
+
}
|
|
1210
|
+
}
|
|
1211
|
+
function isUnanswered(response) {
|
|
1212
|
+
return response === undefined || response === null || typeof response === "string" && response.trim() === "" || Array.isArray(response) && response.length === 0;
|
|
1213
|
+
}
|
|
1214
|
+
function missingRequiredResponseIds(questions, responses) {
|
|
1215
|
+
return questions.filter((question) => {
|
|
1216
|
+
const response = responses[question.id];
|
|
1217
|
+
if (hasRequiredResponse(question, response))
|
|
1218
|
+
return false;
|
|
1219
|
+
if (question.required)
|
|
1220
|
+
return true;
|
|
1221
|
+
return question.type !== "config" && !isUnanswered(response);
|
|
1222
|
+
}).map((question) => question.id);
|
|
1223
|
+
}
|
|
1224
|
+
async function answerApprovalRequest(input) {
|
|
1225
|
+
const { responder } = input;
|
|
1226
|
+
const existing = await getApprovalRequestById2(input.id);
|
|
1227
|
+
if (!existing) {
|
|
1228
|
+
return { kind: "error", status: 404, message: "Approval request not found" };
|
|
1229
|
+
}
|
|
1230
|
+
if (existing.status !== "pending") {
|
|
1231
|
+
const reason = existing.resolutionReason ? `: ${existing.resolutionReason}` : "";
|
|
1232
|
+
return {
|
|
1233
|
+
kind: "error",
|
|
1234
|
+
status: 409,
|
|
1235
|
+
message: `Approval request already resolved with status: ${existing.status}${reason}`
|
|
1236
|
+
};
|
|
1237
|
+
}
|
|
1238
|
+
if (existing.expiresAt && new Date(existing.expiresAt) < new Date) {
|
|
1239
|
+
await getDbClient2().transaction(async () => {
|
|
1240
|
+
const timedOut = await resolveApprovalRequest2(existing.id, {
|
|
1241
|
+
status: "timeout",
|
|
1242
|
+
resolutionReason: `Timed out: the answer arrived after the deadline ${existing.expiresAt}`
|
|
1243
|
+
});
|
|
1244
|
+
if (timedOut && !existing.workflowRunId) {
|
|
1245
|
+
await createApprovalFollowUpTask2(timedOut, "hitl.timeout");
|
|
1246
|
+
}
|
|
1247
|
+
});
|
|
1248
|
+
return {
|
|
1249
|
+
kind: "error",
|
|
1250
|
+
status: 409,
|
|
1251
|
+
message: `Approval request expired at ${existing.expiresAt}`
|
|
1252
|
+
};
|
|
1253
|
+
}
|
|
1254
|
+
const unavailableReason = await getWorkflowApprovalUnavailableReason(existing);
|
|
1255
|
+
if (unavailableReason) {
|
|
1256
|
+
return { kind: "error", status: 409, message: unavailableReason };
|
|
1257
|
+
}
|
|
1258
|
+
const approvers = existing.approvers;
|
|
1259
|
+
if (!isListedApprover(approvers, responder)) {
|
|
1260
|
+
return { kind: "error", status: 403, message: "You are not one of this request's approvers" };
|
|
1261
|
+
}
|
|
1262
|
+
const questions = existing.questions;
|
|
1263
|
+
const missingRequired = missingRequiredResponseIds(questions, input.responses);
|
|
1264
|
+
if (missingRequired.length > 0) {
|
|
1265
|
+
return {
|
|
1266
|
+
kind: "error",
|
|
1267
|
+
status: 400,
|
|
1268
|
+
message: `Responses missing or invalid: ${missingRequired.join(", ")}`
|
|
1269
|
+
};
|
|
1270
|
+
}
|
|
1271
|
+
const configQuestions = questions.filter(isConfigQuestion);
|
|
1272
|
+
const configAnswers = new Map;
|
|
1273
|
+
for (const question of configQuestions) {
|
|
1274
|
+
const state = await readConfigState(question.config);
|
|
1275
|
+
const answer = parseConfigAnswer(question, input.responses[question.id], state);
|
|
1276
|
+
if (!answer.ok) {
|
|
1277
|
+
return { kind: "error", status: 400, message: answer.error };
|
|
1278
|
+
}
|
|
1279
|
+
configAnswers.set(question.id, { question, answer: answer.answer });
|
|
1280
|
+
}
|
|
1281
|
+
if (configAnswers.size > 0 && approvers.policy !== "any") {
|
|
1282
|
+
return { kind: "error", status: 409, message: 'Config questions need approvers.policy "any"' };
|
|
1283
|
+
}
|
|
1284
|
+
const setKeys = [...configAnswers.values()].filter(({ answer }) => answer.action === "set").map(({ question }) => question.config.key);
|
|
1285
|
+
if (setKeys.length > 0) {
|
|
1286
|
+
if (!input.authorizeConfigSet) {
|
|
1287
|
+
return { kind: "error", status: 409, message: "Config values are set on the dashboard" };
|
|
1288
|
+
}
|
|
1289
|
+
if (!await input.authorizeConfigSet(setKeys))
|
|
1290
|
+
return { kind: "handled" };
|
|
1291
|
+
}
|
|
1292
|
+
const safeResponses = { ...input.responses };
|
|
1293
|
+
for (const id of configAnswers.keys())
|
|
1294
|
+
delete safeResponses[id];
|
|
1295
|
+
let status = "approved";
|
|
1296
|
+
for (const q of questions) {
|
|
1297
|
+
if (q.type === "approval") {
|
|
1298
|
+
const answer = safeResponses[q.id];
|
|
1299
|
+
if (answer && answer.approved === false) {
|
|
1300
|
+
status = "rejected";
|
|
1301
|
+
break;
|
|
1302
|
+
}
|
|
1303
|
+
}
|
|
1304
|
+
}
|
|
1305
|
+
const responderId = responderKey(responder);
|
|
1306
|
+
const respondedAt = new Date().toISOString();
|
|
1307
|
+
const configWrites = [];
|
|
1308
|
+
const outcome = await getDbClient2().transaction(async () => {
|
|
1309
|
+
const current = await getApprovalRequestById2(input.id);
|
|
1310
|
+
if (!current || current.status !== "pending")
|
|
1311
|
+
return { kind: "unavailable" };
|
|
1312
|
+
const prior = current.approvals ?? [];
|
|
1313
|
+
if (prior.some((v) => v.responder === responderId))
|
|
1314
|
+
return { kind: "duplicate" };
|
|
1315
|
+
const responses = { ...safeResponses };
|
|
1316
|
+
for (const [id, { question, answer }] of configAnswers) {
|
|
1317
|
+
if (status === "rejected" || answer.action === "skip") {
|
|
1318
|
+
responses[id] = skippedConfigResult(question);
|
|
1319
|
+
} else if (answer.action === "keep") {
|
|
1320
|
+
const kept = await keptConfigResult(question);
|
|
1321
|
+
if (!kept) {
|
|
1322
|
+
throw new ConfigRespondAbort("conflict", `config question "${id}": the key was removed before the answer was saved`);
|
|
1323
|
+
}
|
|
1324
|
+
responses[id] = kept;
|
|
1325
|
+
} else {
|
|
1326
|
+
const written = await applyConfigAnswer(question, answer.value);
|
|
1327
|
+
configWrites.push({ result: written, value: answer.value });
|
|
1328
|
+
responses[id] = written;
|
|
1329
|
+
}
|
|
1330
|
+
}
|
|
1331
|
+
const vote = {
|
|
1332
|
+
responder: responderId,
|
|
1333
|
+
approved: status === "approved",
|
|
1334
|
+
responses,
|
|
1335
|
+
...input.respondedBy ? { claimedRespondedBy: input.respondedBy } : {},
|
|
1336
|
+
...input.via ? { via: input.via } : {},
|
|
1337
|
+
respondedAt
|
|
1338
|
+
};
|
|
1339
|
+
const votes = [...prior, vote];
|
|
1340
|
+
if (status === "rejected" || await approvalQuorumMet(approvers, votes)) {
|
|
1341
|
+
const resolved = await resolveApprovalRequest2(input.id, { status, responses, approvals: votes, resolvedBy: responderId }, { requireActionableWorkflow: true });
|
|
1342
|
+
if (!resolved && configWrites.length > 0)
|
|
1343
|
+
throw new ConfigRespondAbort("unavailable");
|
|
1344
|
+
return resolved ? { kind: "resolved", request: resolved } : { kind: "unavailable" };
|
|
1345
|
+
}
|
|
1346
|
+
const recorded = await recordApprovalVotes2(input.id, votes) ? await getApprovalRequestById2(input.id) : null;
|
|
1347
|
+
return recorded ? { kind: "recorded", request: recorded } : { kind: "unavailable" };
|
|
1348
|
+
}).catch((error) => {
|
|
1349
|
+
if (!(error instanceof ConfigRespondAbort))
|
|
1350
|
+
throw error;
|
|
1351
|
+
configWrites.length = 0;
|
|
1352
|
+
return error.kind === "conflict" ? { kind: "conflict", message: error.message } : { kind: "unavailable" };
|
|
1353
|
+
});
|
|
1354
|
+
if (outcome.kind === "conflict") {
|
|
1355
|
+
return { kind: "error", status: 409, message: outcome.message };
|
|
1356
|
+
}
|
|
1357
|
+
for (const { result, value } of configWrites) {
|
|
1358
|
+
try {
|
|
1359
|
+
await runConfigWriteSideEffects(result.scope, result.key, value);
|
|
1360
|
+
} catch (err) {
|
|
1361
|
+
console.error("[approval-requests] Config side effects failed:", scrubSecrets(err instanceof Error ? err.message : String(err)));
|
|
1362
|
+
}
|
|
1363
|
+
}
|
|
1364
|
+
if (outcome.kind === "duplicate") {
|
|
1365
|
+
return { kind: "error", status: 409, message: "You already answered this approval request" };
|
|
1366
|
+
}
|
|
1367
|
+
if (outcome.kind === "recorded") {
|
|
1368
|
+
return { kind: "recorded", request: outcome.request };
|
|
1369
|
+
}
|
|
1370
|
+
const updated = outcome.kind === "resolved" ? outcome.request : null;
|
|
1371
|
+
if (!updated) {
|
|
1372
|
+
const latest = await getApprovalRequestById2(input.id);
|
|
1373
|
+
const unavailableAfterRace = latest ? await getWorkflowApprovalUnavailableReason(latest) : null;
|
|
1374
|
+
return {
|
|
1375
|
+
kind: "error",
|
|
1376
|
+
status: 409,
|
|
1377
|
+
message: unavailableAfterRace ?? `Failed to resolve approval request (status: ${latest?.status ?? "unknown"})`
|
|
1378
|
+
};
|
|
1379
|
+
}
|
|
1380
|
+
workflowEventBus2.emit("approval.resolved", {
|
|
1381
|
+
requestId: updated.id,
|
|
1382
|
+
status: updated.status,
|
|
1383
|
+
responses: updated.responses,
|
|
1384
|
+
workflowRunId: updated.workflowRunId ?? undefined,
|
|
1385
|
+
workflowRunStepId: updated.workflowRunStepId ?? undefined,
|
|
1386
|
+
sourceTaskId: updated.sourceTaskId ?? undefined
|
|
1387
|
+
});
|
|
1388
|
+
await createApprovalFollowUpTask2(updated, "hitl.follow_up");
|
|
1389
|
+
return { kind: "resolved", request: updated };
|
|
1390
|
+
}
|
|
1391
|
+
async function authorizeHttpConfigSet(req, res, keys) {
|
|
1392
|
+
if (!await ensureConfigAdmin(req, res, "config.write.any"))
|
|
1393
|
+
return false;
|
|
1394
|
+
for (const key of keys) {
|
|
1395
|
+
if (!await ensureHumanOnlyConfigWrite(req, res, key))
|
|
1396
|
+
return false;
|
|
1397
|
+
}
|
|
1398
|
+
const userId = authUserId(getRequestAuth(req));
|
|
1399
|
+
if (userId && isRbacEnabled()) {
|
|
1400
|
+
const grant = await getUserGrant2(userId);
|
|
1401
|
+
if (!grant.grantsAll && !grant.verbs.has("config.write.any")) {
|
|
1402
|
+
jsonError(res, "Forbidden: setting a config value needs 'config.write.any'", 403);
|
|
1403
|
+
return false;
|
|
1404
|
+
}
|
|
1405
|
+
}
|
|
1406
|
+
return true;
|
|
1407
|
+
}
|
|
1408
|
+
async function handleApprovalRequests(req, res, pathSegments, queryParams) {
|
|
1409
|
+
if (respondRoute.match(req.method, pathSegments)) {
|
|
1410
|
+
const parsed = await respondRoute.parse(req, res, pathSegments, queryParams);
|
|
1411
|
+
if (!parsed)
|
|
1412
|
+
return true;
|
|
1413
|
+
const responder = await approvalResponder(req);
|
|
1414
|
+
if (!responder.ok) {
|
|
1415
|
+
jsonError(res, responder.message, 403);
|
|
1416
|
+
return true;
|
|
1417
|
+
}
|
|
1418
|
+
const result = await answerApprovalRequest({
|
|
1419
|
+
id: parsed.params.id,
|
|
1420
|
+
responder: responder.responder,
|
|
1421
|
+
responses: parsed.body.responses,
|
|
1422
|
+
respondedBy: parsed.body.respondedBy,
|
|
1423
|
+
authorizeConfigSet: (keys) => authorizeHttpConfigSet(req, res, keys)
|
|
1424
|
+
});
|
|
1425
|
+
if (result.kind === "handled")
|
|
1426
|
+
return true;
|
|
1427
|
+
if (result.kind === "error") {
|
|
1428
|
+
jsonError(res, result.message, result.status);
|
|
1429
|
+
return true;
|
|
1430
|
+
}
|
|
1431
|
+
respondRoute.respond(res, 200, {
|
|
1432
|
+
approvalRequest: await toApprovalRequestResponse(result.request, result.kind === "resolved" ? { withConfigState: true } : undefined)
|
|
1433
|
+
});
|
|
1434
|
+
return true;
|
|
1435
|
+
}
|
|
1436
|
+
if (cancelRoute.match(req.method, pathSegments)) {
|
|
1437
|
+
const parsed = await cancelRoute.parse(req, res, pathSegments, queryParams);
|
|
1438
|
+
if (!parsed)
|
|
1439
|
+
return true;
|
|
1440
|
+
const { principal, resolvedBy } = await approvalCallerPrincipal(req);
|
|
1441
|
+
const result = await cancelApprovalRequest({
|
|
1442
|
+
id: parsed.params.id,
|
|
1443
|
+
reason: parsed.body.reason,
|
|
1444
|
+
principal,
|
|
1445
|
+
resolvedBy
|
|
1446
|
+
});
|
|
1447
|
+
if (!result.ok) {
|
|
1448
|
+
jsonError(res, result.message, result.status);
|
|
1449
|
+
return true;
|
|
1450
|
+
}
|
|
1451
|
+
cancelRoute.respond(res, 200, {
|
|
1452
|
+
approvalRequest: await toApprovalRequestResponse(result.request),
|
|
1453
|
+
alreadyCancelled: result.alreadyCancelled,
|
|
1454
|
+
runCancelled: result.runCancelled
|
|
1455
|
+
});
|
|
1456
|
+
return true;
|
|
1457
|
+
}
|
|
1458
|
+
if (getByIdRoute.match(req.method, pathSegments)) {
|
|
1459
|
+
const parsed = await getByIdRoute.parse(req, res, pathSegments, queryParams);
|
|
1460
|
+
if (!parsed)
|
|
1461
|
+
return true;
|
|
1462
|
+
const request = await getApprovalRequestById2(parsed.params.id);
|
|
1463
|
+
if (!request) {
|
|
1464
|
+
jsonError(res, "Approval request not found", 404);
|
|
1465
|
+
return true;
|
|
1466
|
+
}
|
|
1467
|
+
getByIdRoute.respond(res, 200, {
|
|
1468
|
+
approvalRequest: await toApprovalRequestResponse(request, { withConfigState: true })
|
|
1469
|
+
});
|
|
1470
|
+
return true;
|
|
1471
|
+
}
|
|
1472
|
+
if (createRoute.match(req.method, pathSegments)) {
|
|
1473
|
+
const parsed = await createRoute.parse(req, res, pathSegments, queryParams);
|
|
1474
|
+
if (!parsed)
|
|
1475
|
+
return true;
|
|
1476
|
+
if (parsed.body.notifications?.some((notification) => notification.channel === "slack")) {
|
|
1477
|
+
const { principal } = await approvalCallerPrincipal(req);
|
|
1478
|
+
const decision = can({ principal, verb: "integration.slack.post", source: "http" });
|
|
1479
|
+
if (!decision.allow) {
|
|
1480
|
+
jsonError(res, SLACK_NOTIFICATION_REFUSED, 403);
|
|
1481
|
+
return true;
|
|
1482
|
+
}
|
|
1483
|
+
}
|
|
1484
|
+
const normalized = await normalizeApprovalQuestions(parsed.body.questions, {
|
|
1485
|
+
approvers: parsed.body.approvers
|
|
1486
|
+
});
|
|
1487
|
+
if (!normalized.ok) {
|
|
1488
|
+
jsonError(res, normalized.error, 400);
|
|
1489
|
+
return true;
|
|
1490
|
+
}
|
|
1491
|
+
const questions = normalized.questions;
|
|
1492
|
+
const id = crypto.randomUUID();
|
|
1493
|
+
const rawCallerAgentId = req.headers["x-agent-id"];
|
|
1494
|
+
const callerAgentId = Array.isArray(rawCallerAgentId) ? rawCallerAgentId[0] : rawCallerAgentId;
|
|
1495
|
+
const createdBy = authUserId(getRequestAuth(req)) ?? await resolveTaskAuditUserId(parsed.body.sourceTaskId, callerAgentId) ?? undefined;
|
|
1496
|
+
const request = await createApprovalRequest2({
|
|
1497
|
+
id,
|
|
1498
|
+
title: parsed.body.title,
|
|
1499
|
+
questions,
|
|
1500
|
+
approvers: parsed.body.approvers,
|
|
1501
|
+
workflowRunId: parsed.body.workflowRunId,
|
|
1502
|
+
workflowRunStepId: parsed.body.workflowRunStepId,
|
|
1503
|
+
sourceTaskId: parsed.body.sourceTaskId,
|
|
1504
|
+
timeoutSeconds: parsed.body.timeoutSeconds,
|
|
1505
|
+
notificationChannels: parsed.body.notifications,
|
|
1506
|
+
createdBy
|
|
1507
|
+
});
|
|
1508
|
+
const notifications = parsed.body.notifications;
|
|
1509
|
+
if (notifications?.length && request.status === "pending") {
|
|
1510
|
+
dispatchApprovalNotifications2({
|
|
1511
|
+
requestId: request.id,
|
|
1512
|
+
title: request.title,
|
|
1513
|
+
questions,
|
|
1514
|
+
timeoutSeconds: parsed.body.timeoutSeconds,
|
|
1515
|
+
notifications
|
|
1516
|
+
}).catch((err) => {
|
|
1517
|
+
console.error("[approval-requests] Unexpected error dispatching notifications:", scrubSecrets(err instanceof Error ? err.message : String(err)));
|
|
1518
|
+
});
|
|
1519
|
+
}
|
|
1520
|
+
createRoute.respond(res, 201, {
|
|
1521
|
+
approvalRequest: await toApprovalRequestResponse(request)
|
|
1522
|
+
});
|
|
1523
|
+
return true;
|
|
1524
|
+
}
|
|
1525
|
+
if (listRoute.match(req.method, pathSegments)) {
|
|
1526
|
+
const parsed = await listRoute.parse(req, res, pathSegments, queryParams);
|
|
1527
|
+
if (!parsed)
|
|
1528
|
+
return true;
|
|
1529
|
+
const filters = {
|
|
1530
|
+
status: parsed.query.status || undefined,
|
|
1531
|
+
workflowRunId: parsed.query.workflowRunId || undefined,
|
|
1532
|
+
limit: parsed.query.limit || undefined
|
|
1533
|
+
};
|
|
1534
|
+
if (parsed.query.fields === "slim") {
|
|
1535
|
+
const viewer = await approvalResponder(req);
|
|
1536
|
+
listRoute.respond(res, 200, {
|
|
1537
|
+
approvalRequests: await withApprovalProgress(await listApprovalRequestSummaries2(filters), viewer.ok ? viewer.responder : null)
|
|
1538
|
+
});
|
|
1539
|
+
return true;
|
|
1540
|
+
}
|
|
1541
|
+
const requests = await listApprovalRequests2(filters);
|
|
1542
|
+
listRoute.respond(res, 200, {
|
|
1543
|
+
approvalRequests: await Promise.all(requests.map((request) => toApprovalRequestResponse(request)))
|
|
1544
|
+
});
|
|
1545
|
+
return true;
|
|
1546
|
+
}
|
|
1547
|
+
return false;
|
|
1548
|
+
}
|
|
1549
|
+
async function approvalCallerPrincipal(req) {
|
|
1550
|
+
const rawAgentId = req.headers["x-agent-id"];
|
|
1551
|
+
const headerAgentId = Array.isArray(rawAgentId) ? rawAgentId[0] : rawAgentId;
|
|
1552
|
+
const principal = await agentFirstPrincipal(req, headerAgentId);
|
|
1553
|
+
const resolvedBy = principal.kind === "user" ? principal.userId : principal.kind === "agent" ? principal.agentId : principal.kind === "operator" ? "operator" : null;
|
|
1554
|
+
return { principal, resolvedBy };
|
|
1555
|
+
}
|
|
1556
|
+
function userMatchesListed(user, listed) {
|
|
1557
|
+
if (listed === user.id)
|
|
1558
|
+
return true;
|
|
1559
|
+
return !!user.email && listed.toLowerCase() === user.email.toLowerCase();
|
|
1560
|
+
}
|
|
1561
|
+
function isListedApprover(approvers, responder) {
|
|
1562
|
+
const users = approvers.users ?? [];
|
|
1563
|
+
const roles = approvers.roles ?? [];
|
|
1564
|
+
if (users.length === 0 && roles.length === 0)
|
|
1565
|
+
return true;
|
|
1566
|
+
if (responder.kind === "operator")
|
|
1567
|
+
return true;
|
|
1568
|
+
const { user } = responder;
|
|
1569
|
+
if (users.some((listed) => userMatchesListed(user, listed)))
|
|
1570
|
+
return true;
|
|
1571
|
+
return !!user.role && roles.includes(user.role);
|
|
1572
|
+
}
|
|
1573
|
+
async function approvalProgress(approvers, votes) {
|
|
1574
|
+
const approving = votes.filter((v) => v.approved);
|
|
1575
|
+
const distinct = new Set(approving.map((v) => v.responder)).size;
|
|
1576
|
+
const policy = approvers.policy;
|
|
1577
|
+
if (policy === "any")
|
|
1578
|
+
return { approved: Math.min(distinct, 1), required: 1 };
|
|
1579
|
+
if (policy === "all") {
|
|
1580
|
+
const listed = approvers.users ?? [];
|
|
1581
|
+
if (listed.length === 0)
|
|
1582
|
+
return { approved: Math.min(distinct, 1), required: 1 };
|
|
1583
|
+
const approvingUsers = [];
|
|
1584
|
+
for (const vote of approving) {
|
|
1585
|
+
if (vote.responder === "operator")
|
|
1586
|
+
continue;
|
|
1587
|
+
const user = await findUserById(vote.responder);
|
|
1588
|
+
approvingUsers.push(user ?? { id: vote.responder });
|
|
1589
|
+
}
|
|
1590
|
+
const approved = listed.filter((entry) => approvingUsers.some((u) => userMatchesListed(u, entry))).length;
|
|
1591
|
+
return { approved, required: listed.length };
|
|
1592
|
+
}
|
|
1593
|
+
return { approved: Math.min(distinct, policy.min), required: policy.min };
|
|
1594
|
+
}
|
|
1595
|
+
async function approvalQuorumMet(approvers, votes) {
|
|
1596
|
+
const { approved, required } = await approvalProgress(approvers, votes);
|
|
1597
|
+
return approved >= required;
|
|
1598
|
+
}
|
|
1599
|
+
var QuestionSchema, QuestionInputSchema, ApproversSchema, NotificationChannelSchema, ApprovalVoteSchema, ApprovalProgressSchema, ApprovalRequestSchema, ApprovalRequestSummarySchema, ConfigRespondAbort, createRoute, getByIdRoute, respondRoute, cancelRoute, listRoute, SLACK_NOTIFICATION_REFUSED = "Slack notifications require lead privileges (integration.slack.post). Create the request without them, or ask the lead to post the link.";
|
|
1600
|
+
var init_approval_requests = __esm(() => {
|
|
1601
|
+
init_zod();
|
|
1602
|
+
init_approval_config_question();
|
|
1603
|
+
init_audit_user();
|
|
1604
|
+
init_db4();
|
|
1605
|
+
init_rbac_roles();
|
|
1606
|
+
init_users();
|
|
1607
|
+
init_rbac();
|
|
1608
|
+
init_request_auth_context();
|
|
1609
|
+
init_secret_scrubber();
|
|
1610
|
+
init_approval_cancel();
|
|
1611
|
+
init_approval_notifications();
|
|
1612
|
+
init_event_bus();
|
|
1613
|
+
init_config();
|
|
1614
|
+
init_person_responder();
|
|
1615
|
+
init_request_principal();
|
|
1616
|
+
init_route_def();
|
|
1617
|
+
init_utils2();
|
|
1618
|
+
QuestionSchema = object2({
|
|
1619
|
+
id: string2(),
|
|
1620
|
+
type: _enum2(["approval", "text", "single-select", "multi-select", "boolean", "config"]),
|
|
1621
|
+
label: string2(),
|
|
1622
|
+
required: boolean().optional(),
|
|
1623
|
+
description: string2().optional(),
|
|
1624
|
+
placeholder: string2().optional(),
|
|
1625
|
+
multiline: boolean().optional(),
|
|
1626
|
+
options: array2(object2({
|
|
1627
|
+
value: string2(),
|
|
1628
|
+
label: string2(),
|
|
1629
|
+
description: string2().optional()
|
|
1630
|
+
})).optional(),
|
|
1631
|
+
minSelections: number2().int().min(0).optional(),
|
|
1632
|
+
maxSelections: number2().int().min(1).optional(),
|
|
1633
|
+
defaultValue: boolean().optional(),
|
|
1634
|
+
config: ConfigQuestionSettingsSchema.optional().describe("Config question settings. Answers are written to swarm_config and replaced by a result that never holds a secret value.")
|
|
1635
|
+
});
|
|
1636
|
+
QuestionInputSchema = QuestionSchema.extend({
|
|
1637
|
+
label: string2().optional(),
|
|
1638
|
+
required: boolean().default(true)
|
|
1639
|
+
});
|
|
1640
|
+
ApproversSchema = object2({
|
|
1641
|
+
users: array2(string2()).optional(),
|
|
1642
|
+
roles: array2(string2()).optional(),
|
|
1643
|
+
policy: union3([literal2("any"), literal2("all"), object2({ min: number2().int().min(1) })])
|
|
1644
|
+
});
|
|
1645
|
+
NotificationChannelSchema = object2({
|
|
1646
|
+
channel: _enum2(["slack", "email"]),
|
|
1647
|
+
target: string2(),
|
|
1648
|
+
messageTs: string2().optional()
|
|
1649
|
+
});
|
|
1650
|
+
ApprovalVoteSchema = object2({
|
|
1651
|
+
responder: string2().describe("Who answered, from the credential: a user id, or `operator` for the shared key."),
|
|
1652
|
+
approved: boolean(),
|
|
1653
|
+
responses: record2(string2(), unknown()),
|
|
1654
|
+
claimedRespondedBy: string2().optional().describe("The `respondedBy` the client sent. Unverified; display only."),
|
|
1655
|
+
respondedAt: string2(),
|
|
1656
|
+
via: object2({ channel: string2(), platformUserId: string2() }).optional().describe("Set when the answer came from a chat button: the channel and the platform user.")
|
|
1657
|
+
});
|
|
1658
|
+
ApprovalProgressSchema = object2({
|
|
1659
|
+
approved: number2().int().describe("Approvals that count toward the policy so far."),
|
|
1660
|
+
required: number2().int().describe("Approvals the policy needs before the request resolves.")
|
|
1661
|
+
}).nullable().describe("Quorum progress while the request is pending; null once it is resolved.");
|
|
1662
|
+
ApprovalRequestSchema = object2({
|
|
1663
|
+
id: string2(),
|
|
1664
|
+
title: string2(),
|
|
1665
|
+
questions: array2(QuestionSchema),
|
|
1666
|
+
workflowRunId: string2().nullable(),
|
|
1667
|
+
workflowRunStepId: string2().nullable(),
|
|
1668
|
+
sourceTaskId: string2().nullable(),
|
|
1669
|
+
approvers: ApproversSchema,
|
|
1670
|
+
status: _enum2(["pending", "approved", "rejected", "timeout", "cancelled"]),
|
|
1671
|
+
responses: record2(string2(), unknown()).nullable(),
|
|
1672
|
+
approvals: array2(ApprovalVoteSchema).nullable().describe("Every accepted answer, in order. A request with an `all` or `{ min: N }` policy stays pending until enough approve."),
|
|
1673
|
+
approvalProgress: ApprovalProgressSchema,
|
|
1674
|
+
resolvedBy: string2().nullable().describe("Who resolved the request, from the credential: a user id, `operator` for the shared key, or an agent id for a cancellation."),
|
|
1675
|
+
resolvedAt: string2().nullable(),
|
|
1676
|
+
resolutionReason: string2().nullable(),
|
|
1677
|
+
timeoutSeconds: number2().nullable(),
|
|
1678
|
+
expiresAt: string2().nullable(),
|
|
1679
|
+
notificationChannels: array2(NotificationChannelSchema).nullable(),
|
|
1680
|
+
createdBy: string2().optional(),
|
|
1681
|
+
createdAt: string2(),
|
|
1682
|
+
updatedAt: string2(),
|
|
1683
|
+
configState: record2(string2(), ConfigStateSchema).optional().describe("Live state of each config question's key, by question id. Read at request time and never stored. `value` appears only for non-secret keys.")
|
|
1684
|
+
});
|
|
1685
|
+
ApprovalRequestSummarySchema = ApprovalRequestSchema.omit({
|
|
1686
|
+
questions: true,
|
|
1687
|
+
approvers: true,
|
|
1688
|
+
responses: true,
|
|
1689
|
+
approvals: true,
|
|
1690
|
+
resolutionReason: true,
|
|
1691
|
+
notificationChannels: true,
|
|
1692
|
+
configState: true
|
|
1693
|
+
}).extend({
|
|
1694
|
+
questionCount: number2().int(),
|
|
1695
|
+
viewerCanRespond: boolean().optional().describe("Pending rows only: whether the caller may answer, by the same rule as the respond route (a listed user or role, or no users and roles listed).")
|
|
1696
|
+
});
|
|
1697
|
+
ConfigRespondAbort = class ConfigRespondAbort extends Error {
|
|
1698
|
+
kind;
|
|
1699
|
+
constructor(kind, message = kind) {
|
|
1700
|
+
super(message);
|
|
1701
|
+
this.kind = kind;
|
|
1702
|
+
}
|
|
1703
|
+
};
|
|
1704
|
+
createRoute = route({
|
|
1705
|
+
method: "post",
|
|
1706
|
+
path: "/api/approval-requests",
|
|
1707
|
+
pattern: ["api", "approval-requests"],
|
|
1708
|
+
session: bodyTask("sourceTaskId"),
|
|
1709
|
+
summary: "Create a new approval request",
|
|
1710
|
+
tags: ["ApprovalRequests"],
|
|
1711
|
+
body: object2({
|
|
1712
|
+
title: string2().min(1),
|
|
1713
|
+
questions: array2(QuestionInputSchema).min(1).describe('A request with a `config` question needs `approvers.policy: "any"`. The answer is written to swarm_config; the request stores only `{ key, scope, scopeId, isSecret, status, updatedAt }` (plus `value` for non-secret keys).'),
|
|
1714
|
+
approvers: object2({
|
|
1715
|
+
users: array2(string2()).optional(),
|
|
1716
|
+
roles: array2(string2()).optional(),
|
|
1717
|
+
policy: union3([
|
|
1718
|
+
literal2("any"),
|
|
1719
|
+
literal2("all"),
|
|
1720
|
+
object2({ min: number2().int().min(1) })
|
|
1721
|
+
])
|
|
1722
|
+
}),
|
|
1723
|
+
workflowRunId: string2().uuid().optional(),
|
|
1724
|
+
workflowRunStepId: string2().uuid().optional(),
|
|
1725
|
+
sourceTaskId: string2().uuid().optional(),
|
|
1726
|
+
timeoutSeconds: number2().int().min(1).optional().describe("Seconds until the request expires. After that the request becomes 'timeout' and you get a hitl-follow-up task. A request with no timeout is cancelled after APPROVAL_REQUEST_AUTO_CANCELLATION_DAYS days (default 7)."),
|
|
1727
|
+
notifications: array2(object2({
|
|
1728
|
+
channel: _enum2(["slack", "email"]),
|
|
1729
|
+
target: string2()
|
|
1730
|
+
})).optional().describe("Where to announce the request. A Slack target (channel or user ID) gets a card with the title, the questions and a link to the dashboard page that answers it. Slack targets need a lead agent caller (403 otherwise). Email is not supported yet and is skipped.")
|
|
1731
|
+
}),
|
|
1732
|
+
responses: {
|
|
1733
|
+
201: {
|
|
1734
|
+
description: "Approval request created",
|
|
1735
|
+
schema: object2({ approvalRequest: ApprovalRequestSchema })
|
|
1736
|
+
},
|
|
1737
|
+
400: { description: "Validation error" },
|
|
1738
|
+
403: { description: "Slack notifications require a lead agent" }
|
|
1739
|
+
},
|
|
1740
|
+
auth: { apiKey: true }
|
|
1741
|
+
});
|
|
1742
|
+
getByIdRoute = route({
|
|
1743
|
+
method: "get",
|
|
1744
|
+
path: "/api/approval-requests/{id}",
|
|
1745
|
+
pattern: ["api", "approval-requests", null],
|
|
1746
|
+
summary: "Get approval request details",
|
|
1747
|
+
tags: ["ApprovalRequests"],
|
|
1748
|
+
params: object2({ id: string2().uuid() }),
|
|
1749
|
+
responses: {
|
|
1750
|
+
200: {
|
|
1751
|
+
description: "Approval request details",
|
|
1752
|
+
schema: object2({ approvalRequest: ApprovalRequestSchema })
|
|
1753
|
+
},
|
|
1754
|
+
404: { description: "Not found" }
|
|
1755
|
+
},
|
|
1756
|
+
auth: { apiKey: true },
|
|
1757
|
+
description: "Includes `configState` when the request has `config` questions: the live state of each target key, read now."
|
|
1758
|
+
});
|
|
1759
|
+
respondRoute = route({
|
|
1760
|
+
method: "post",
|
|
1761
|
+
path: "/api/approval-requests/{id}/respond",
|
|
1762
|
+
pattern: ["api", "approval-requests", null, "respond"],
|
|
1763
|
+
summary: "Submit a response to an approval request",
|
|
1764
|
+
description: 'Only a person may answer: a user token, a page session signed for a user, or the shared key with no agent identity (recorded as `operator`). The responder is taken from the credential. When the request lists `approvers.users` or `approvers.roles`, a user must match one of them. A rejection resolves the request at once; approvals resolve it when the `any`, `all` or `{ min: N }` policy is met, and until then it stays pending with the answer recorded in `approvals`. A `config` question takes `{ action: "set", value }`, `{ action: "keep" }` (key must exist) or `{ action: "skip" }` (optional questions only); `set` also needs the config write permission. The value is written only when the request is approved, and the stored answer is the result, never a secret value.',
|
|
1765
|
+
tags: ["ApprovalRequests"],
|
|
1766
|
+
params: object2({ id: string2().uuid() }),
|
|
1767
|
+
body: object2({
|
|
1768
|
+
responses: record2(string2(), unknown()),
|
|
1769
|
+
respondedBy: string2().optional().describe("Unverified display name. Stored as `claimedRespondedBy` on the answer; never used as the responder.")
|
|
1770
|
+
}),
|
|
1771
|
+
responses: {
|
|
1772
|
+
200: {
|
|
1773
|
+
description: "Response recorded. `status` stays `pending` while the policy needs more approvals.",
|
|
1774
|
+
schema: object2({ approvalRequest: ApprovalRequestSchema })
|
|
1775
|
+
},
|
|
1776
|
+
400: { description: "Validation error" },
|
|
1777
|
+
403: { description: "Caller is an agent, or is not one of the request's approvers" },
|
|
1778
|
+
404: { description: "Not found" },
|
|
1779
|
+
409: { description: "Already resolved, or this responder already answered" }
|
|
1780
|
+
},
|
|
1781
|
+
auth: { apiKey: true },
|
|
1782
|
+
rbac: { permission: "approval.respond" }
|
|
1783
|
+
});
|
|
1784
|
+
cancelRoute = route({
|
|
1785
|
+
method: "post",
|
|
1786
|
+
path: "/api/approval-requests/{id}/cancel",
|
|
1787
|
+
pattern: ["api", "approval-requests", null, "cancel"],
|
|
1788
|
+
summary: "Cancel a pending approval request",
|
|
1789
|
+
tags: ["ApprovalRequests"],
|
|
1790
|
+
params: object2({ id: string2().uuid() }),
|
|
1791
|
+
body: object2({ reason: string2().max(500).optional() }),
|
|
1792
|
+
responses: {
|
|
1793
|
+
200: {
|
|
1794
|
+
description: "Request cancelled, or already cancelled. A request that gates a running or waiting workflow run cancels that run too.",
|
|
1795
|
+
schema: object2({
|
|
1796
|
+
approvalRequest: ApprovalRequestSchema,
|
|
1797
|
+
alreadyCancelled: boolean(),
|
|
1798
|
+
runCancelled: boolean()
|
|
1799
|
+
})
|
|
1800
|
+
},
|
|
1801
|
+
403: { description: "Caller may not cancel this request" },
|
|
1802
|
+
404: { description: "Not found" },
|
|
1803
|
+
409: {
|
|
1804
|
+
description: "Already resolved with approved, rejected, or timeout, or its expiresAt passed"
|
|
1805
|
+
}
|
|
1806
|
+
},
|
|
1807
|
+
auth: { apiKey: true },
|
|
1808
|
+
rbac: { permission: "approval.cancel.any" }
|
|
1809
|
+
});
|
|
1810
|
+
listRoute = route({
|
|
1811
|
+
method: "get",
|
|
1812
|
+
path: "/api/approval-requests",
|
|
1813
|
+
pattern: ["api", "approval-requests"],
|
|
1814
|
+
summary: "List approval requests with optional filters",
|
|
1815
|
+
description: "Returns full approval requests by default. Pass `fields=slim` for the list-view shape: `questions`, `approvers`, `responses`, `resolutionReason` and `notificationChannels` are dropped and `questionCount` is added, plus `viewerCanRespond` on pending rows. Fetch one request in full via `GET /api/approval-requests/{id}`.",
|
|
1816
|
+
tags: ["ApprovalRequests"],
|
|
1817
|
+
query: object2({
|
|
1818
|
+
status: string2().optional(),
|
|
1819
|
+
workflowRunId: string2().optional(),
|
|
1820
|
+
limit: exports_coerce.number().optional(),
|
|
1821
|
+
fields: _enum2(["full", "slim"]).optional()
|
|
1822
|
+
}),
|
|
1823
|
+
responses: {
|
|
1824
|
+
200: {
|
|
1825
|
+
description: "List of approval requests",
|
|
1826
|
+
schema: object2({
|
|
1827
|
+
approvalRequests: union3([
|
|
1828
|
+
array2(ApprovalRequestSchema),
|
|
1829
|
+
array2(ApprovalRequestSummarySchema)
|
|
1830
|
+
])
|
|
1831
|
+
})
|
|
1832
|
+
}
|
|
1833
|
+
},
|
|
1834
|
+
auth: { apiKey: true }
|
|
1835
|
+
});
|
|
1836
|
+
});
|
|
1837
|
+
|
|
1838
|
+
// src/ui-spec/actions.ts
|
|
1839
|
+
async function runTaskUiAction({
|
|
1840
|
+
taskId,
|
|
1841
|
+
actionId,
|
|
1842
|
+
surface,
|
|
1843
|
+
actorUserId,
|
|
1844
|
+
slackUserId
|
|
1845
|
+
}) {
|
|
1846
|
+
if (!isEnvFlagEnabled("UI_SPEC_ACTIONS_ENABLED", false))
|
|
1847
|
+
return { status: "disabled" };
|
|
1848
|
+
const task = await getTaskById2(taskId);
|
|
1849
|
+
const stored = task ? await getTaskUiSpec(taskId) : null;
|
|
1850
|
+
const action = stored?.actions && Object.hasOwn(stored.actions, actionId) ? stored.actions[actionId] : undefined;
|
|
1851
|
+
if (!task || !stored || !action)
|
|
1852
|
+
return { status: "unknown_action" };
|
|
1853
|
+
if (!actorUserId || actorUserId !== task.requestedByUserId)
|
|
1854
|
+
return { status: "forbidden" };
|
|
1855
|
+
if (action.kind === "script") {
|
|
1856
|
+
return await runTaskUiScriptAction({
|
|
1857
|
+
task,
|
|
1858
|
+
actionId,
|
|
1859
|
+
action,
|
|
1860
|
+
stored,
|
|
1861
|
+
surface,
|
|
1862
|
+
actorUserId,
|
|
1863
|
+
slackUserId
|
|
1864
|
+
});
|
|
1865
|
+
}
|
|
1866
|
+
const reserved = await reserveTaskUiActionRun({
|
|
1867
|
+
taskId,
|
|
1868
|
+
actionId,
|
|
1869
|
+
surface,
|
|
1870
|
+
slackUserId,
|
|
1871
|
+
userId: actorUserId
|
|
1872
|
+
});
|
|
1873
|
+
if (reserved === "exists")
|
|
1874
|
+
return { status: "already_done" };
|
|
1875
|
+
let followUp;
|
|
1876
|
+
try {
|
|
1877
|
+
const lead = await getLeadAgent2();
|
|
1878
|
+
followUp = await createTaskWithSiblingAwareness(action.prompt, {
|
|
1879
|
+
agentId: lead?.id,
|
|
1880
|
+
routingReason: lead ? "skill" : undefined,
|
|
1881
|
+
routingSource: lead ? "engine_default" : undefined,
|
|
1882
|
+
source: surface === "slack" ? "slack" : "ui",
|
|
1883
|
+
parentTaskId: taskId,
|
|
1884
|
+
inheritParentOutputSchema: false,
|
|
1885
|
+
slackChannelId: task.slackChannelId,
|
|
1886
|
+
slackThreadTs: task.slackThreadTs,
|
|
1887
|
+
slackUserId,
|
|
1888
|
+
requestedByUserId: actorUserId,
|
|
1889
|
+
contextKey: task.slackChannelId && task.slackThreadTs ? slackContextKey({ channelId: task.slackChannelId, threadTs: task.slackThreadTs }) : undefined
|
|
1890
|
+
}, { origin: surface === "slack" ? "slack" : "rest" });
|
|
1891
|
+
} catch (error) {
|
|
1892
|
+
await releaseTaskUiActionRun(taskId, actionId);
|
|
1893
|
+
throw error;
|
|
1894
|
+
}
|
|
1895
|
+
await setTaskUiActionResult(taskId, actionId, followUp.id);
|
|
1896
|
+
return { status: "started", taskId: followUp.id };
|
|
1897
|
+
}
|
|
1898
|
+
var init_actions = __esm(() => {
|
|
1899
|
+
init_db4();
|
|
1900
|
+
init_task_ui_spec();
|
|
1901
|
+
init_context_key();
|
|
1902
|
+
init_sibling_awareness();
|
|
1903
|
+
init_env_flag();
|
|
1904
|
+
init_script_actions();
|
|
1905
|
+
});
|
|
1906
|
+
|
|
1907
|
+
export { runTaskUiAction, init_actions, globalConfig, init_global_config, telemetryProxyEndpoint, handleUsedBy, init_used_by, handleRanking, init_ranking, readsRepoSecrets, requestSecretReadScope, ensureConfigAdmin, runConfigWriteSideEffects, ensureHttpPermission, handleConfig, init_config, approvalResponder, responderKey, userApprovalResponder, init_person_responder, answerApprovalRequest, handleApprovalRequests, init_approval_requests };
|