@desplega.ai/agent-swarm 2.8.0 → 2.8.2
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-t949vbbp.js → acp-adapter-fqzkxyra.js} +3 -3
- package/dist/{actions-7e9czc7s.js → actions-kxek041g.js} +18 -18
- package/dist/{amp-adapter-gv6cbb7d.js → amp-adapter-ce7jjke4.js} +1 -1
- package/dist/{app-b9fbkp9v.js → app-v6zz8yh0.js} +3 -3
- package/dist/{assistant-wjb7v4c7.js → assistant-m0sw9xx2.js} +19 -19
- package/dist/{boot-args-schema-2t37e0fe.js → boot-args-schema-66bk37wv.js} +1 -1
- package/dist/{boot-reembed-gka3zas7.js → boot-reembed-edjpwsc1.js} +1 -1
- package/dist/{boot-reembed-a35nkyr1.js → boot-reembed-y27n09tz.js} +1 -1
- package/dist/{boot-scrub-sweep-65sdnp6c.js → boot-scrub-sweep-1xc35965.js} +3 -3
- package/dist/{boot-seeds-x42tzytw.js → boot-seeds-7hjj91qj.js} +4 -4
- package/dist/{boxd-qbkxy6ap.js → boxd-ent8ch04.js} +1 -1
- package/dist/{claude-adapter-v221b2fd.js → claude-adapter-stw7jdcf.js} +3 -3
- package/dist/{claude-managed-adapter-29eq09wd.js → claude-managed-adapter-jh6c523j.js} +2 -2
- package/dist/{claude-managed-setup-9m6450zk.js → claude-managed-setup-y6z2perp.js} +5 -5
- package/dist/{claude-sdk-session-0q0ptaba.js → claude-sdk-session-vvya8wqk.js} +3 -3
- package/dist/{cli-wk18cm92.js → cli-0cq8y6m7.js} +1 -1
- package/dist/{cli-p1w18yhx.js → cli-1pz0330a.js} +1 -1
- package/dist/{cli-y97qxcfx.js → cli-1qkz151v.js} +3 -3
- package/dist/{cli-qwca7s44.js → cli-26ctbcdp.js} +18 -6
- package/dist/{cli-8fknbnhw.js → cli-2kvhc7x8.js} +7 -7
- package/dist/{cli-rfywm85n.js → cli-3e875j5p.js} +136 -49
- package/dist/{cli-6wxjceza.js → cli-3sy2xags.js} +10 -10
- package/dist/{cli-a7wvp2km.js → cli-3vmb0n58.js} +1 -1
- package/dist/{cli-p1bq50aa.js → cli-4vzgeta4.js} +13 -13
- package/dist/{cli-m28atx8q.js → cli-5y340nzn.js} +4 -4
- package/dist/{cli-7p1kvkck.js → cli-6rc5frdm.js} +1 -1
- package/dist/{cli-tph5wt3y.js → cli-6wj7p986.js} +1 -1
- package/dist/{cli-t73cas91.js → cli-7349va39.js} +8100 -7620
- package/dist/{cli-ee0b971j.js → cli-837vfs2x.js} +2 -2
- package/dist/{cli-abejgen1.js → cli-959kp5h2.js} +12 -11
- package/dist/{cli-8kzasymh.js → cli-97ae65rz.js} +4 -4
- package/dist/{cli-m4dqmnbp.js → cli-9mb2q6pb.js} +1 -1
- package/dist/{cli-p2gfst4m.js → cli-a0z912j7.js} +123 -35
- package/dist/{cli-4txa0ter.js → cli-b98a65ed.js} +3 -3
- package/dist/{cli-k0wwfqbg.js → cli-dns0y538.js} +4 -0
- package/dist/{cli-tk7cjj8h.js → cli-dzpc6en0.js} +1 -1
- package/dist/{cli-qa4wdgsy.js → cli-e1p3n5gq.js} +4 -4
- package/dist/{cli-gxkx0zzp.js → cli-f4e8r23x.js} +1 -1
- package/dist/{cli-qmqk2yc2.js → cli-f4r3g076.js} +1 -1
- package/dist/{cli-wcg8x116.js → cli-f6bahpn5.js} +1 -1
- package/dist/{cli-qsnnd04k.js → cli-fpjmegdb.js} +1 -1
- package/dist/{cli-j790gp2w.js → cli-fwy8kfd6.js} +271 -37
- package/dist/{cli-rmmpt0wm.js → cli-g5mtmf6t.js} +6 -6
- package/dist/{cli-rzsy6nc6.js → cli-gyt3zydq.js} +3 -3
- package/dist/{cli-pasjcnmj.js → cli-j24zbska.js} +3 -3
- package/dist/{cli-qfedvmcr.js → cli-jdknh18m.js} +10 -10
- package/dist/{cli-7b8sbmag.js → cli-kjtwrhea.js} +1 -1
- package/dist/{cli-gpwhbgx0.js → cli-m9s2qff2.js} +57 -25
- package/dist/{cli-2wnq8jkz.js → cli-mxn1qvbn.js} +3 -2
- package/dist/{cli-s7t6p9my.js → cli-n6vtrcht.js} +1 -1
- package/dist/{cli-2zp0et3v.js → cli-pchypa1s.js} +55 -19
- package/dist/{cli-yq3zak69.js → cli-pfs8adn4.js} +1 -1
- package/dist/{cli-c55z5chy.js → cli-q24n86d2.js} +2 -2
- package/dist/{cli-h38x262p.js → cli-rcecc3yq.js} +167 -43
- package/dist/{cli-xae4g51r.js → cli-rh15cakt.js} +1 -1
- package/dist/{cli-sdtt3men.js → cli-rmzsadkf.js} +1 -1
- package/dist/{cli-f3vq58d2.js → cli-t2tma8gb.js} +1 -1
- package/dist/{cli-m23zjcy2.js → cli-tekytdq9.js} +2 -2
- package/dist/{cli-tqegb8eq.js → cli-vdektqgf.js} +1 -1
- package/dist/{cli-ffhtssbp.js → cli-vj75tyaw.js} +1 -1
- package/dist/{cli-deefvewm.js → cli-w401b9tq.js} +1 -1
- package/dist/{cli-n9ftpys4.js → cli-x6t50dmw.js} +7 -7
- package/dist/{cli-6t09sdhy.js → cli-xf3qw745.js} +3 -3
- package/dist/{cli-hxpyc9sn.js → cli-z1w943va.js} +2 -2
- package/dist/{cli-334z18y3.js → cli-zh9rsbqf.js} +3 -3
- package/dist/cli.js +17 -17
- package/dist/{codex-adapter-30j9bpzd.js → codex-adapter-zerf5qsp.js} +1 -1
- package/dist/{codex-hook-h3vk6xzr.js → codex-hook-30gyhzxe.js} +1 -1
- package/dist/{codex-session-runner-8vp57v8w.js → codex-session-runner-89s304py.js} +1 -1
- package/dist/{commands-bngnz9g7.js → commands-jeh1b51j.js} +3 -3
- package/dist/{controller-hxx8wwy1.js → controller-mctfbrse.js} +3 -3
- package/dist/{controllers-connect-e2b4gyxc.js → controllers-connect-nxa1ddwn.js} +19 -19
- package/dist/{cursor-adapter-n5nc3mfe.js → cursor-adapter-qj8vehv6.js} +1 -1
- package/dist/{db-bgm7vkc0.js → db-2dvay0es.js} +3 -3
- package/dist/{db-c6np41ca.js → db-b36qn6k3.js} +2 -2
- package/dist/{dispatcher-jnybck15.js → dispatcher-gndbta01.js} +17 -17
- package/dist/{dsh-adapter-nrhbrjz8.js → dsh-adapter-f75sz821.js} +1 -1
- package/dist/{e2b-jkwfhbcv.js → e2b-3gpc2n3w.js} +1 -1
- package/dist/{e2b-s16txnpx.js → e2b-jbm7mj93.js} +1 -1
- package/dist/{embedding-space-crsm2zp0.js → embedding-space-4p05vb2x.js} +6 -6
- package/dist/{embeddings-e7z3f27f.js → embeddings-m6768mgh.js} +1 -1
- package/dist/{external-channel-m77wf5z3.js → external-channel-gjv3jne3.js} +2 -2
- package/dist/{fx-adapter-b6w0kf56.js → fx-adapter-rpsgb1tw.js} +4 -4
- package/dist/{grok-adapter-4sqtebdk.js → grok-adapter-n2m3zjg1.js} +4 -4
- package/dist/handlers-nv8edn19.js +32 -0
- package/dist/{heartbeat-xgb036sx.js → heartbeat-a1tv60gt.js} +20 -20
- package/dist/{hook-xsk1jbha.js → hook-8h5dzcgq.js} +2 -2
- package/dist/{hook-5h02c9ga.js → hook-cyaps9ba.js} +4 -4
- package/dist/{http-txe7qhvn.js → http-t15mhbd9.js} +1733 -79
- package/dist/{index-0eny15vj.js → index-2skqtd76.js} +2 -2
- package/dist/{index-w7em4ktq.js → index-d6wkh8ar.js} +2 -2
- package/dist/{index-rvccek1w.js → index-gjwaqaq8.js} +5 -5
- package/dist/{index-e5pfbsys.js → index-hjhfk3ra.js} +3 -3
- package/dist/{index-1qw6f2dc.js → index-khe3gp0k.js} +4 -4
- package/dist/index-ksmyd6kc.js +37 -0
- package/dist/{index-vk63emp7.js → index-qav6455f.js} +14 -12
- package/dist/index-rjnrje98.js +32 -0
- package/dist/index-tv3413wy.js +33 -0
- package/dist/{index-ysvbhg5m.js → index-w1zqf680.js} +1 -1
- package/dist/{keepalive-4zsrce78.js → keepalive-91s7hzrb.js} +3 -3
- package/dist/lead-3hmddvrm.js +70 -0
- package/dist/{maintenance-86jvartk.js → maintenance-7pjmy5xy.js} +1 -1
- package/dist/{node-je82wjet.js → node-4c5jqxr3.js} +1 -1
- package/dist/{oauth-refresh-sweep-j52kg9pr.js → oauth-refresh-sweep-rzqfm94j.js} +2 -2
- package/dist/{onboard-c2aj5p8q.js → onboard-74st7pag.js} +3 -3
- package/dist/{opencode-adapter-dsagkhtw.js → opencode-adapter-arn7gm8q.js} +2 -2
- package/dist/{otel-impl-yyy203z8.js → otel-impl-rnzey8cb.js} +1 -1
- package/dist/{pi-mono-adapter-546cd1cc.js → pi-mono-adapter-6mkwq64n.js} +3 -2
- package/dist/{pricing-refresh-1rgzqyzz.js → pricing-refresh-ha21jhk7.js} +2 -2
- package/dist/{rbac-roles-e70xfeyj.js → rbac-roles-59dxachk.js} +2 -2
- package/dist/{rbac-roles-q89qe8er.js → rbac-roles-wqhma4dr.js} +3 -3
- package/dist/{render-v2-k6tt107q.js → render-v2-14kpzx12.js} +3 -3
- package/dist/{resume-cnnrjfxa.js → resume-gsa5fb5f.js} +6 -6
- package/dist/{session-access-xkxkjw3n.js → session-access-skm7bnp6.js} +4 -4
- package/dist/{session-source-backfill-1d5pdwww.js → session-source-backfill-pbqzbncv.js} +2 -2
- package/dist/{setup-se8q7gkc.js → setup-5yermsem.js} +1 -1
- package/dist/{work-objects-1kxnbzy5.js → work-objects-xj0ck0w4.js} +20 -20
- package/dist/{worker-follow-up-zqm8apt4.js → worker-follow-up-911xc0b8.js} +19 -17
- package/dist/worker-qgg0m2gw.js +70 -0
- package/openapi.json +1741 -290
- package/package.json +3 -3
- package/src/apps/catalog.generated.json +120 -1
- package/src/apps/definition.ts +38 -11
- package/src/apps/page-validator.ts +88 -0
- package/src/be/db/model-profiles.ts +110 -11
- package/src/be/db/tasks/read.ts +20 -0
- package/src/be/db/workflow-run-definitions.ts +19 -8
- package/src/be/db-client.ts +43 -5
- package/src/be/db.ts +9 -3
- package/src/be/migrations/284_model_profile_fallbacks.sql +9 -0
- package/src/be/model-profile-check.ts +43 -18
- package/src/be/runtime-pools/routing.ts +1 -0
- package/src/be/savings/calibrate.ts +468 -0
- package/src/be/savings/compute.ts +182 -0
- package/src/be/savings/model.ts +406 -0
- package/src/be/scripts/typecheck.ts +5 -0
- package/src/be/seed/agent-fs-provision.ts +48 -11
- package/src/be/seed/workflows-seeder.ts +67 -23
- package/src/be/skill-parser.ts +19 -7
- package/src/commands/onboard/agent-fs-version.ts +1 -1
- package/src/commands/provider-error-class.ts +97 -0
- package/src/commands/runner.ts +99 -17
- package/src/extensions/contract-types.generated.ts +1 -1
- package/src/http/all-routes.ts +2 -0
- package/src/http/fs.ts +8 -2
- package/src/http/index.ts +4 -0
- package/src/http/model-profiles.ts +43 -10
- package/src/http/poll.ts +1 -0
- package/src/http/savings-calibration.ts +277 -0
- package/src/http/savings.ts +363 -0
- package/src/http/tasks.ts +46 -4
- package/src/http/trackers/authorize-gate.ts +41 -0
- package/src/http/trackers/jira.ts +26 -4
- package/src/http/trackers/linear.ts +26 -4
- package/src/integrations/chat-sdk/limits.ts +6 -1
- package/src/jira/oauth.ts +7 -1
- package/src/linear/README.md +2 -1
- package/src/linear/oauth.ts +7 -1
- package/src/providers/amp-adapter.ts +1 -1
- package/src/providers/codex-adapter.ts +3 -0
- package/src/providers/pi-mono-adapter.ts +6 -5
- package/src/providers/types.ts +7 -0
- package/src/scripts-runtime/eval-harness.ts +14 -1
- package/src/scripts-runtime/executors/types.ts +3 -0
- package/src/scripts-runtime/sdk-allowlist.ts +11 -1
- package/src/scripts-runtime/swarm-sdk.ts +6 -0
- package/src/scripts-runtime/types/stdlib.d.ts +9 -0
- package/src/scripts-runtime/types/swarm-extension.d.ts +34 -0
- package/src/scripts-runtime/types/swarm-sdk.d.ts +9 -0
- package/src/tasks/worker-follow-up.ts +142 -3
- package/src/tests/agent-fs-provision-seeder.test.ts +81 -0
- package/src/tests/apps-chart-shell.test.ts +170 -0
- package/src/tests/apps-icon.test.ts +156 -2
- package/src/tests/chat-sdk-relay.test.ts +12 -0
- package/src/tests/codex-adapter.test.ts +11 -0
- package/src/tests/comb-default.test.ts +6 -0
- package/src/tests/core-auth.test.ts +7 -6
- package/src/tests/db-client-busy-retry.test.ts +58 -6
- package/src/tests/deploy-guard.test.ts +154 -0
- package/src/tests/docs-index-footprint.test.js +3 -3
- package/src/tests/fixtures/app-shell-charts-definition.json.txt +180 -0
- package/src/tests/mcp-tools.test.ts +1 -1
- package/src/tests/model-profile-fallbacks.test.ts +482 -0
- package/src/tests/model-profiles-api.test.ts +1 -0
- package/src/tests/pi-mono-session-cost-on-abort.test.ts +115 -0
- package/src/tests/provider-error-class.test.ts +174 -0
- package/src/tests/runner-provider-fallback.test.ts +197 -0
- package/src/tests/savings-calibration-api.test.ts +264 -0
- package/src/tests/savings-calibration.test.ts +201 -0
- package/src/tests/savings-compute.test.ts +406 -0
- package/src/tests/savings-model.test.ts +287 -0
- package/src/tests/script-connections.test.ts +2 -0
- package/src/tests/script-native-unawaited-drain.test.ts +167 -0
- package/src/tests/sdk-allowlist.test.ts +40 -0
- package/src/tests/seed-workflows.test.ts +167 -11
- package/src/tests/skill-parser.test.ts +45 -0
- package/src/tests/tracker-oauth-authorize-auth.test.ts +262 -0
- package/src/tests/workflow-definition-pinning.test.ts +128 -3
- package/src/tests/workflow-script-principal.test.ts +94 -4
- package/src/tools/app-upsert.ts +1 -1
- package/src/tools/model-profiles/list-model-profiles.ts +4 -2
- package/src/tools/script-run.ts +1 -1
- package/src/tools/update-profile.ts +1 -1
- package/src/types.ts +115 -33
- package/src/utils/constants.ts +2 -0
- package/templates/skills/apps/SKILL.md +62 -3
- package/templates/skills/apps/content.md +62 -3
- package/templates/skills/swarm-docs/content.md +2 -0
- package/templates/skills/swarm-scripts/SKILL.md +1 -1
- package/templates/skills/swarm-scripts/content.md +1 -1
- package/dist/handlers-kdjcyzdj.js +0 -32
- package/dist/index-835xdgnm.js +0 -33
- package/dist/index-d469300x.js +0 -37
- package/dist/index-rzqwp11g.js +0 -32
- package/dist/lead-yqt47dkr.js +0 -70
- package/dist/worker-j6xxtq7p.js +0 -70
|
@@ -0,0 +1,363 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { getSwarmConfigs, getWorkflow } from "../be/db";
|
|
4
|
+
import { computeWorkflowWindow, type SavingsSql, type WorkflowWindow } from "../be/savings/compute";
|
|
5
|
+
import {
|
|
6
|
+
type Calibration,
|
|
7
|
+
parseCalibration,
|
|
8
|
+
priceWorkflow,
|
|
9
|
+
SAVINGS_CALIBRATION_KEY,
|
|
10
|
+
SAVINGS_TIERS,
|
|
11
|
+
type SavingsBand,
|
|
12
|
+
SHIPPED_CALIBRATION,
|
|
13
|
+
splitByDay,
|
|
14
|
+
} from "../be/savings/model";
|
|
15
|
+
import { executeReadOnlyQueryGated } from "./db-query";
|
|
16
|
+
import {
|
|
17
|
+
DbQueryConcurrencyCapError,
|
|
18
|
+
DbQueryTimeoutError,
|
|
19
|
+
getDbQueryHttpBudgetMs,
|
|
20
|
+
} from "./db-query-shared";
|
|
21
|
+
import { route } from "./route-def";
|
|
22
|
+
import { json } from "./utils";
|
|
23
|
+
|
|
24
|
+
/** Live facts are reused for this long, so page views do not rescan the runs. */
|
|
25
|
+
const FACTS_TTL_MS = 10 * 60 * 1000;
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* The scans run through the bounded db-query executor: a child process with a
|
|
29
|
+
* wall-clock budget, sharing the swarm-wide db-query concurrency cap, so a
|
|
30
|
+
* burst of requests can neither block the API's event loop nor pile up.
|
|
31
|
+
*/
|
|
32
|
+
export const boundedSql: SavingsSql = async <T>(sql: string, params: unknown[]) => {
|
|
33
|
+
const result = await executeReadOnlyQueryGated(sql, params, getDbQueryHttpBudgetMs(), 10_000);
|
|
34
|
+
return result.rows.map((row) =>
|
|
35
|
+
Object.fromEntries(result.columns.map((column, i) => [column, row[i]])),
|
|
36
|
+
) as T[];
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
const SavingsBandSchema = z.object({ p10: z.number(), p50: z.number(), p90: z.number() });
|
|
40
|
+
|
|
41
|
+
const SavingsJobRowSchema = z.object({
|
|
42
|
+
kind: z.literal("workflow"),
|
|
43
|
+
workflowId: z.string(),
|
|
44
|
+
name: z.string(),
|
|
45
|
+
basis: z.literal("modelled"),
|
|
46
|
+
runs: z.number().int(),
|
|
47
|
+
substitutedRuns: z.number().int(),
|
|
48
|
+
effectRuns: z.number().int(),
|
|
49
|
+
enabledOnlyRuns: z.number().int(),
|
|
50
|
+
capApplied: z.boolean(),
|
|
51
|
+
opsPerRun: z.number(),
|
|
52
|
+
measuredUsd: z
|
|
53
|
+
.number()
|
|
54
|
+
.describe(
|
|
55
|
+
"Measured spend of every run in the window: agent tasks, their reviews, recorded LLM cost.",
|
|
56
|
+
),
|
|
57
|
+
estimatedLlmUsd: z
|
|
58
|
+
.number()
|
|
59
|
+
.describe(
|
|
60
|
+
"LLM spend estimated from tokens and output size, not measured. 0 when the runs recorded their LLM cost.",
|
|
61
|
+
),
|
|
62
|
+
actualUsd: z
|
|
63
|
+
.number()
|
|
64
|
+
.describe(
|
|
65
|
+
"Scaled estimate, not a measurement: `measuredUsd + estimatedLlmUsd` times `substitutedRuns / runs`. The saving subtracts this.",
|
|
66
|
+
),
|
|
67
|
+
agentOnlyUsd: SavingsBandSchema,
|
|
68
|
+
savingUsd: SavingsBandSchema,
|
|
69
|
+
actualHours: z
|
|
70
|
+
.number()
|
|
71
|
+
.describe("Scaled estimate: measured hours times `substitutedRuns / runs`."),
|
|
72
|
+
agentOnlyHours: SavingsBandSchema,
|
|
73
|
+
hoursSaved: SavingsBandSchema,
|
|
74
|
+
agentOnlyUsdPerRun: z.number(),
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
const SavingsJobsResponseSchema = z.object({
|
|
78
|
+
window: z.object({ start: z.string(), end: z.string(), days: z.number().int() }),
|
|
79
|
+
tier: z.enum(SAVINGS_TIERS),
|
|
80
|
+
calibrationModel: z.string(),
|
|
81
|
+
calibratedAt: z.string(),
|
|
82
|
+
/** `shipped`: the constants in the release. `deployment`: derived from this swarm's own sessions. */
|
|
83
|
+
calibrationSource: z.enum(["shipped", "deployment"]),
|
|
84
|
+
computedAt: z.string(),
|
|
85
|
+
/** False when there is nothing to show: no runs, or too many runs to compute live. */
|
|
86
|
+
valid: z.boolean(),
|
|
87
|
+
reason: z.enum(["no-runs", "too-many-runs"]).nullable(),
|
|
88
|
+
rows: z.array(SavingsJobRowSchema),
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
const savingsJobsRoute = route({
|
|
92
|
+
method: "get",
|
|
93
|
+
path: "/api/savings/jobs",
|
|
94
|
+
pattern: ["api", "savings", "jobs"],
|
|
95
|
+
summary: "Estimated automation savings for a workflow",
|
|
96
|
+
description:
|
|
97
|
+
"What the workflow's runs in the window would have cost as agent tasks, minus what they cost. `measuredUsd` is the measured spend and `estimatedLlmUsd` the LLM spend estimated where none was recorded; `actualUsd` is their sum scaled to the substituted share of runs, the estimate the saving subtracts. Modelled at the chosen tier, with an 80% range (p10 to p90). `valid` is false when the workflow had no runs, or more runs than the live computation handles.",
|
|
98
|
+
tags: ["Savings"],
|
|
99
|
+
query: z.object({
|
|
100
|
+
workflowId: z.string().min(1),
|
|
101
|
+
days: z.enum(["7", "30", "90"]).default("30").transform(Number),
|
|
102
|
+
tier: z.enum(SAVINGS_TIERS).default("smart"),
|
|
103
|
+
}),
|
|
104
|
+
responses: {
|
|
105
|
+
200: { description: "Savings rows for the workflow", schema: SavingsJobsResponseSchema },
|
|
106
|
+
400: { description: "Missing workflowId, or an unknown days or tier value" },
|
|
107
|
+
404: { description: "Workflow not found" },
|
|
108
|
+
408: { description: "A savings query ran past its time budget" },
|
|
109
|
+
429: { description: "Too many concurrent database queries; retry shortly" },
|
|
110
|
+
},
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
const SavingsDailyResponseSchema = z.object({
|
|
114
|
+
window: z.object({ start: z.string(), end: z.string(), days: z.number().int() }),
|
|
115
|
+
tier: z.enum(SAVINGS_TIERS),
|
|
116
|
+
calibrationModel: z.string(),
|
|
117
|
+
calibratedAt: z.string(),
|
|
118
|
+
calibrationSource: z.enum(["shipped", "deployment"]),
|
|
119
|
+
computedAt: z.string(),
|
|
120
|
+
valid: z.boolean(),
|
|
121
|
+
reason: z.enum(["no-runs", "too-many-runs"]).nullable(),
|
|
122
|
+
/** One point per UTC day in the window, oldest first; empty when not valid. */
|
|
123
|
+
points: z.array(
|
|
124
|
+
z.object({
|
|
125
|
+
day: z.string(),
|
|
126
|
+
/** p50; the points sum to the p50 saving of `/api/savings/jobs`. */
|
|
127
|
+
savingUsd: z.number(),
|
|
128
|
+
/** Scaled estimate; the points sum to the jobs row's `actualUsd`. */
|
|
129
|
+
actualUsd: z
|
|
130
|
+
.number()
|
|
131
|
+
.describe(
|
|
132
|
+
"Scaled estimate: the day's measured and estimated spend times the window's substituted share.",
|
|
133
|
+
),
|
|
134
|
+
/** Measured; the points sum to the jobs row's `measuredUsd`. */
|
|
135
|
+
measuredUsd: z.number().describe("The day's measured spend, not scaled."),
|
|
136
|
+
/** Estimated; the points sum to the jobs row's `estimatedLlmUsd`. */
|
|
137
|
+
estimatedLlmUsd: z
|
|
138
|
+
.number()
|
|
139
|
+
.describe("The day's LLM spend estimated from tokens and output size, not measured."),
|
|
140
|
+
}),
|
|
141
|
+
),
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
const savingsDailyRoute = route({
|
|
145
|
+
method: "get",
|
|
146
|
+
path: "/api/savings/daily",
|
|
147
|
+
pattern: ["api", "savings", "daily"],
|
|
148
|
+
summary: "Daily automation savings for a workflow",
|
|
149
|
+
description:
|
|
150
|
+
"The workflow's p50 saving, measured spend and scaled actual cost per UTC day of the window, from the same computation as `/api/savings/jobs`, so the points sum to its p50 saving, `measuredUsd`, `estimatedLlmUsd` and `actualUsd`. When the hourly cap applies, the counted schedule runs are spread pro rata over the days. `valid` is false when the workflow had no runs, or more runs than the live computation handles.",
|
|
151
|
+
tags: ["Savings"],
|
|
152
|
+
query: z.object({
|
|
153
|
+
workflowId: z.string().min(1),
|
|
154
|
+
days: z.enum(["7", "30", "90"]).default("30").transform(Number),
|
|
155
|
+
tier: z.enum(SAVINGS_TIERS).default("smart"),
|
|
156
|
+
}),
|
|
157
|
+
responses: {
|
|
158
|
+
200: {
|
|
159
|
+
description: "Daily savings points for the workflow",
|
|
160
|
+
schema: SavingsDailyResponseSchema,
|
|
161
|
+
},
|
|
162
|
+
400: { description: "Missing workflowId, or an unknown days or tier value" },
|
|
163
|
+
404: { description: "Workflow not found" },
|
|
164
|
+
408: { description: "A savings query ran past its time budget" },
|
|
165
|
+
429: { description: "Too many concurrent database queries; retry shortly" },
|
|
166
|
+
},
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
type CachedFacts = { at: number; start: string; end: string; result: Promise<WorkflowWindow> };
|
|
170
|
+
const factsCache = new Map<string, CachedFacts>();
|
|
171
|
+
|
|
172
|
+
/** The stored deployment curve is re-read this often, so a new calibration shows within a minute. */
|
|
173
|
+
const CALIBRATION_TTL_MS = 60 * 1000;
|
|
174
|
+
let calibrationCache: { at: number; value: Calibration } | null = null;
|
|
175
|
+
|
|
176
|
+
async function activeCalibration(now: number): Promise<Calibration> {
|
|
177
|
+
if (calibrationCache && now - calibrationCache.at < CALIBRATION_TTL_MS) {
|
|
178
|
+
return calibrationCache.value;
|
|
179
|
+
}
|
|
180
|
+
const [row] = await getSwarmConfigs({ scope: "global", key: SAVINGS_CALIBRATION_KEY });
|
|
181
|
+
// A malformed row falls back to the shipped curve rather than failing every savings request.
|
|
182
|
+
const value = parseCalibration(row?.value) ?? SHIPPED_CALIBRATION;
|
|
183
|
+
calibrationCache = { at: now, value };
|
|
184
|
+
return value;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** Forget the cached curve, so the next savings request reads the stored row. */
|
|
188
|
+
export function clearCalibrationCache(): void {
|
|
189
|
+
calibrationCache = null;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** Test hook. */
|
|
193
|
+
export function resetSavingsCache(): void {
|
|
194
|
+
factsCache.clear();
|
|
195
|
+
clearCalibrationCache();
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function cachedWindow(
|
|
199
|
+
workflow: { id: string; definition: unknown },
|
|
200
|
+
days: number,
|
|
201
|
+
now: number,
|
|
202
|
+
): CachedFacts {
|
|
203
|
+
const key = `${workflow.id}:${days}`;
|
|
204
|
+
const hit = factsCache.get(key);
|
|
205
|
+
if (hit && now - hit.at < FACTS_TTL_MS) return hit;
|
|
206
|
+
const end = new Date(now).toISOString();
|
|
207
|
+
const start = new Date(now - days * 86_400_000).toISOString();
|
|
208
|
+
const entry: CachedFacts = {
|
|
209
|
+
at: now,
|
|
210
|
+
start,
|
|
211
|
+
end,
|
|
212
|
+
result: computeWorkflowWindow(workflow, { start, end }, boundedSql),
|
|
213
|
+
};
|
|
214
|
+
// A failed computation is not cached.
|
|
215
|
+
void entry.result.catch(() => factsCache.delete(key));
|
|
216
|
+
factsCache.set(key, entry);
|
|
217
|
+
return entry;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const round2 = (x: number) => Math.round(x * 100) / 100;
|
|
221
|
+
const roundBand = (b: SavingsBand): SavingsBand => ({
|
|
222
|
+
p10: round2(b.p10),
|
|
223
|
+
p50: round2(b.p50),
|
|
224
|
+
p90: round2(b.p90),
|
|
225
|
+
});
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* Round each value to cents so the rounded values sum to the rounded total
|
|
229
|
+
* (largest remainder), keeping the chart equal to the header amount.
|
|
230
|
+
*/
|
|
231
|
+
export function roundToTotal(values: number[]): number[] {
|
|
232
|
+
const cents = values.map((v) => v * 100);
|
|
233
|
+
const floors = cents.map(Math.floor);
|
|
234
|
+
let left = Math.round(cents.reduce((s, c) => s + c, 0)) - floors.reduce((s, c) => s + c, 0);
|
|
235
|
+
const order = cents
|
|
236
|
+
.map((c, i) => ({ i, r: c - (floors[i] as number) }))
|
|
237
|
+
.sort((a, b) => b.r - a.r);
|
|
238
|
+
for (const { i } of order) {
|
|
239
|
+
if (left <= 0) break;
|
|
240
|
+
floors[i] = (floors[i] as number) + 1;
|
|
241
|
+
left--;
|
|
242
|
+
}
|
|
243
|
+
return floors.map((c) => c / 100);
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** Every UTC day from `start` to `end`, both inclusive. */
|
|
247
|
+
function utcDays(start: string, end: string): string[] {
|
|
248
|
+
const out: string[] = [];
|
|
249
|
+
for (let t = Date.parse(start.slice(0, 10)); t <= Date.parse(end); t += 86_400_000) {
|
|
250
|
+
out.push(new Date(t).toISOString().slice(0, 10));
|
|
251
|
+
}
|
|
252
|
+
return out;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
export async function handleSavings(
|
|
256
|
+
req: IncomingMessage,
|
|
257
|
+
res: ServerResponse,
|
|
258
|
+
pathSegments: string[],
|
|
259
|
+
queryParams: URLSearchParams,
|
|
260
|
+
): Promise<boolean> {
|
|
261
|
+
const isJobs = savingsJobsRoute.match(req.method, pathSegments);
|
|
262
|
+
if (!isJobs && !savingsDailyRoute.match(req.method, pathSegments)) return false;
|
|
263
|
+
const parsed = isJobs
|
|
264
|
+
? await savingsJobsRoute.parse(req, res, pathSegments, queryParams)
|
|
265
|
+
: await savingsDailyRoute.parse(req, res, pathSegments, queryParams);
|
|
266
|
+
if (!parsed) return true;
|
|
267
|
+
const { workflowId, days, tier } = parsed.query;
|
|
268
|
+
const workflow = await getWorkflow(workflowId);
|
|
269
|
+
if (!workflow) {
|
|
270
|
+
res.writeHead(404, { "Content-Type": "application/json" });
|
|
271
|
+
res.end(JSON.stringify({ error: "Workflow not found" }));
|
|
272
|
+
return true;
|
|
273
|
+
}
|
|
274
|
+
const entry = cachedWindow(workflow, days, Date.now());
|
|
275
|
+
let result: WorkflowWindow;
|
|
276
|
+
try {
|
|
277
|
+
result = await entry.result;
|
|
278
|
+
} catch (err) {
|
|
279
|
+
if (err instanceof DbQueryConcurrencyCapError) {
|
|
280
|
+
res.setHeader("Retry-After", "1");
|
|
281
|
+
json(res, { error: "db_query_concurrency_cap", message: err.message }, 429);
|
|
282
|
+
return true;
|
|
283
|
+
}
|
|
284
|
+
if (err instanceof DbQueryTimeoutError) {
|
|
285
|
+
json(res, { error: "db_query_timeout", message: err.message }, 408);
|
|
286
|
+
return true;
|
|
287
|
+
}
|
|
288
|
+
throw err;
|
|
289
|
+
}
|
|
290
|
+
const calibration = await activeCalibration(Date.now());
|
|
291
|
+
const base = {
|
|
292
|
+
window: { start: entry.start, end: entry.end, days },
|
|
293
|
+
tier,
|
|
294
|
+
calibrationModel: calibration.model,
|
|
295
|
+
calibratedAt: calibration.calibratedAt,
|
|
296
|
+
calibrationSource: calibration.source,
|
|
297
|
+
computedAt: new Date(entry.at).toISOString(),
|
|
298
|
+
};
|
|
299
|
+
if (result.status === "too-many-runs" || result.facts.runs === 0) {
|
|
300
|
+
const reason = result.status === "too-many-runs" ? "too-many-runs" : "no-runs";
|
|
301
|
+
if (isJobs) savingsJobsRoute.respond(res, 200, { ...base, valid: false, reason, rows: [] });
|
|
302
|
+
else savingsDailyRoute.respond(res, 200, { ...base, valid: false, reason, points: [] });
|
|
303
|
+
return true;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
if (!isJobs) {
|
|
307
|
+
const split = new Map(
|
|
308
|
+
splitByDay(result.facts, result.byDay, { tier, days, curve: calibration.curve }).map((p) => [
|
|
309
|
+
p.day,
|
|
310
|
+
p,
|
|
311
|
+
]),
|
|
312
|
+
);
|
|
313
|
+
const dayList = utcDays(entry.start, entry.end);
|
|
314
|
+
const saving = roundToTotal(dayList.map((d) => split.get(d)?.savingUsd ?? 0));
|
|
315
|
+
const actual = roundToTotal(dayList.map((d) => split.get(d)?.actualUsd ?? 0));
|
|
316
|
+
const measured = roundToTotal(dayList.map((d) => split.get(d)?.measuredUsd ?? 0));
|
|
317
|
+
const estimated = roundToTotal(dayList.map((d) => split.get(d)?.estimatedLlmUsd ?? 0));
|
|
318
|
+
savingsDailyRoute.respond(res, 200, {
|
|
319
|
+
...base,
|
|
320
|
+
valid: true,
|
|
321
|
+
reason: null,
|
|
322
|
+
points: dayList.map((day, i) => ({
|
|
323
|
+
day,
|
|
324
|
+
savingUsd: saving[i] as number,
|
|
325
|
+
actualUsd: actual[i] as number,
|
|
326
|
+
measuredUsd: measured[i] as number,
|
|
327
|
+
estimatedLlmUsd: estimated[i] as number,
|
|
328
|
+
})),
|
|
329
|
+
});
|
|
330
|
+
return true;
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
const priced = priceWorkflow(result.facts, { tier, days, band: "job", curve: calibration.curve });
|
|
334
|
+
savingsJobsRoute.respond(res, 200, {
|
|
335
|
+
...base,
|
|
336
|
+
valid: true,
|
|
337
|
+
reason: null,
|
|
338
|
+
rows: [
|
|
339
|
+
{
|
|
340
|
+
kind: "workflow",
|
|
341
|
+
workflowId: workflow.id,
|
|
342
|
+
name: workflow.name,
|
|
343
|
+
basis: "modelled",
|
|
344
|
+
runs: priced.runs,
|
|
345
|
+
substitutedRuns: priced.substitutedRuns,
|
|
346
|
+
effectRuns: priced.effectRuns,
|
|
347
|
+
enabledOnlyRuns: priced.enabledOnlyRuns,
|
|
348
|
+
capApplied: priced.capApplied,
|
|
349
|
+
opsPerRun: round2(priced.opsPerRun),
|
|
350
|
+
measuredUsd: round2(priced.measuredUsd),
|
|
351
|
+
estimatedLlmUsd: round2(priced.estimatedLlmUsd),
|
|
352
|
+
actualUsd: round2(priced.actualUsd),
|
|
353
|
+
agentOnlyUsd: roundBand(priced.agentOnlyUsd),
|
|
354
|
+
savingUsd: roundBand(priced.savingUsd),
|
|
355
|
+
actualHours: round2(priced.actualHours),
|
|
356
|
+
agentOnlyHours: roundBand(priced.agentOnlyHours),
|
|
357
|
+
hoursSaved: roundBand(priced.hoursSaved),
|
|
358
|
+
agentOnlyUsdPerRun: round2(priced.agentOnlyUsdPerRun),
|
|
359
|
+
},
|
|
360
|
+
],
|
|
361
|
+
});
|
|
362
|
+
return true;
|
|
363
|
+
}
|
package/src/http/tasks.ts
CHANGED
|
@@ -63,7 +63,11 @@ import { TaskCreationBlockedError } from "../tasks/errors";
|
|
|
63
63
|
import { createTaskWithSiblingAwareness } from "../tasks/sibling-awareness";
|
|
64
64
|
import { finalizeSkippedTaskReaction, skipReasonFrom } from "../tasks/task-skip";
|
|
65
65
|
import { guardTerminalTaskResultWrite } from "../tasks/terminal-result-guard";
|
|
66
|
-
import {
|
|
66
|
+
import {
|
|
67
|
+
createResumeFollowUp,
|
|
68
|
+
createWorkerTaskFollowUp,
|
|
69
|
+
nextFallback,
|
|
70
|
+
} from "../tasks/worker-follow-up";
|
|
67
71
|
import {
|
|
68
72
|
AgentLogSchema,
|
|
69
73
|
type AgentTask,
|
|
@@ -73,10 +77,12 @@ import {
|
|
|
73
77
|
type AgentTaskStatus,
|
|
74
78
|
AgentTaskStatusSchema,
|
|
75
79
|
AssetKeySchema,
|
|
80
|
+
type FallbackHop,
|
|
76
81
|
isTerminalTaskStatus,
|
|
77
82
|
ModelProfileCredentialsSchema,
|
|
78
83
|
ModelTierSchema,
|
|
79
84
|
OnUnsupportedSchema,
|
|
85
|
+
ProviderErrorClassSchema,
|
|
80
86
|
ProviderNameSchema,
|
|
81
87
|
ReasoningEffortSchema,
|
|
82
88
|
ResumeReasonSchema,
|
|
@@ -92,6 +98,7 @@ import {
|
|
|
92
98
|
import { ensure } from "../utils/business-use";
|
|
93
99
|
import { getRequestAuth } from "../utils/request-auth-context";
|
|
94
100
|
import { scrubSecrets } from "../utils/secret-scrubber";
|
|
101
|
+
import { readsRepoSecrets } from "./config";
|
|
95
102
|
import { createListTotalCache, LIST_TOTAL_TTL_MS } from "./list-total-cache";
|
|
96
103
|
import {
|
|
97
104
|
agentFirstPrincipal,
|
|
@@ -226,10 +233,12 @@ const FinishTaskConflictSchema = z.object({
|
|
|
226
233
|
|
|
227
234
|
const SupersedeTaskResponseSchema = z.object({
|
|
228
235
|
success: z.literal(true),
|
|
229
|
-
kind: z.enum(["alreadyFinished", "workflow-failed", "resumed"]),
|
|
236
|
+
kind: z.enum(["alreadyFinished", "workflow-failed", "resumed", "noFallback"]),
|
|
230
237
|
task: AgentTaskSchema.nullable(),
|
|
231
238
|
resumeTaskId: z.string().nullable(),
|
|
232
239
|
resumeTaskStatus: AgentTaskStatusSchema.optional(),
|
|
240
|
+
/** `noFallback` only: why the chain ended, to lead the worker's failure reason. */
|
|
241
|
+
failureReason: z.string().nullable().optional(),
|
|
233
242
|
});
|
|
234
243
|
|
|
235
244
|
// ─── Route Definitions ───────────────────────────────────────────────────────
|
|
@@ -765,10 +774,15 @@ const supersedeTaskRoute = route({
|
|
|
765
774
|
session: { taskParam: "id" },
|
|
766
775
|
summary: "Supersede an in-progress task (terminate + spawn resume follow-up)",
|
|
767
776
|
description:
|
|
768
|
-
'Marks the original task `superseded` (terminal) and creates a fresh `taskType="resume"` follow-up so a worker can pick up the work in a new provider session. Workflow-step tasks (those with `workflowRunStepId`) are carved out: the original is marked `failed` with reason `superseded_workflow_task` and no follow-up is created — the workflow engine\'s retry/failure policy applies.',
|
|
777
|
+
'Marks the original task `superseded` (terminal) and creates a fresh `taskType="resume"` follow-up so a worker can pick up the work in a new provider session. Workflow-step tasks (those with `workflowRunStepId`) are carved out: the original is marked `failed` with reason `superseded_workflow_task` and no follow-up is created — the workflow engine\'s retry/failure policy applies. With `reason: provider_fallback` (and its `errorClass`), the resume runs on the same agent with the next fallback profile that passes the profile check; when none is left, or the task is a workflow step, nothing changes and `kind: noFallback` tells the worker to fail the task itself, led by `failureReason` when set.',
|
|
769
778
|
tags: ["Tasks"],
|
|
770
779
|
params: z.object({ id: z.string() }),
|
|
771
|
-
body: z
|
|
780
|
+
body: z
|
|
781
|
+
.object({ reason: ResumeReasonSchema, errorClass: ProviderErrorClassSchema.optional() })
|
|
782
|
+
.refine((body) => (body.reason === "provider_fallback") === (body.errorClass !== undefined), {
|
|
783
|
+
message: "`errorClass` is required with `reason: provider_fallback` and only allowed with it",
|
|
784
|
+
path: ["errorClass"],
|
|
785
|
+
}),
|
|
772
786
|
auth: { apiKey: true, agentId: true },
|
|
773
787
|
responses: {
|
|
774
788
|
200: {
|
|
@@ -2146,6 +2160,33 @@ export async function handleTasks(
|
|
|
2146
2160
|
return true;
|
|
2147
2161
|
}
|
|
2148
2162
|
|
|
2163
|
+
// Provider error: pick the next fallback before touching the task. No
|
|
2164
|
+
// pick (or a workflow step, whose engine owns retries) leaves it running,
|
|
2165
|
+
// and the worker fails it with the real error, as without fallbacks.
|
|
2166
|
+
let fallback: { profile: string; hop: FallbackHop } | undefined;
|
|
2167
|
+
if (parsed.body.reason === "provider_fallback" && parsed.body.errorClass) {
|
|
2168
|
+
const pick =
|
|
2169
|
+
task.workflowRunStepId == null
|
|
2170
|
+
? await nextFallback(task, parsed.body.errorClass, {
|
|
2171
|
+
includeRepoSecrets: readsRepoSecrets(
|
|
2172
|
+
getRequestAuth(req),
|
|
2173
|
+
task.agentId ? await getAgentById(task.agentId) : null,
|
|
2174
|
+
),
|
|
2175
|
+
})
|
|
2176
|
+
: ({ kind: "none", message: null } as const);
|
|
2177
|
+
if (pick.kind === "none") {
|
|
2178
|
+
supersedeTaskRoute.respond(res, 200, {
|
|
2179
|
+
success: true,
|
|
2180
|
+
kind: "noFallback",
|
|
2181
|
+
task,
|
|
2182
|
+
resumeTaskId: null,
|
|
2183
|
+
failureReason: pick.message,
|
|
2184
|
+
});
|
|
2185
|
+
return true;
|
|
2186
|
+
}
|
|
2187
|
+
fallback = { profile: pick.profile, hop: pick.hop };
|
|
2188
|
+
}
|
|
2189
|
+
|
|
2149
2190
|
// Workflow-step tasks: fail back to the engine instead of superseding.
|
|
2150
2191
|
// Check this BEFORE the supersede UPDATE so we don't leave a workflow
|
|
2151
2192
|
// step in `superseded` if the engine expects `failed`.
|
|
@@ -2205,6 +2246,7 @@ export async function handleTasks(
|
|
|
2205
2246
|
const followUp = await createResumeFollowUp({
|
|
2206
2247
|
parentId: parsed.params.id,
|
|
2207
2248
|
reason: parsed.body.reason,
|
|
2249
|
+
fallback,
|
|
2208
2250
|
});
|
|
2209
2251
|
|
|
2210
2252
|
// `workflow-skip` is unreachable here (workflow-step path branched above).
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { resolveHttpAuditUserId } from "../../be/audit-user";
|
|
4
|
+
import { ensureHttpPermission } from "../config";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Query for `GET /api/trackers/{linear,jira}/authorize`. `format=json` returns
|
|
8
|
+
* the consent URL instead of a 302, so a browser client can send its bearer
|
|
9
|
+
* on a `fetch` and then navigate to the provider itself.
|
|
10
|
+
*/
|
|
11
|
+
export const TrackerAuthorizeQuerySchema = z.object({
|
|
12
|
+
redirect: z.string().optional(),
|
|
13
|
+
format: z.enum(["redirect", "json"]).optional(),
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
export const TrackerAuthorizeUrlSchema = z.object({ authorizeUrl: z.string() });
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Starting a tracker OAuth flow lands the provider's tokens on the swarm-wide
|
|
20
|
+
* `default` authorization, so it takes the same permission as the generic
|
|
21
|
+
* `POST /api/oauth-apps/{id}/authorize-url` route. Writes a 403 and returns
|
|
22
|
+
* null on denial; otherwise returns the initiating user (null for the operator
|
|
23
|
+
* key or an agent) to record on the pending row.
|
|
24
|
+
*/
|
|
25
|
+
export async function ensureTrackerAuthorizeAdmin(
|
|
26
|
+
req: IncomingMessage,
|
|
27
|
+
res: ServerResponse,
|
|
28
|
+
providerName: string,
|
|
29
|
+
): Promise<{ userId: string | null } | null> {
|
|
30
|
+
const header = req.headers["x-agent-id"];
|
|
31
|
+
const agentId = Array.isArray(header) ? header[0] : header;
|
|
32
|
+
const allowed = await ensureHttpPermission(
|
|
33
|
+
req,
|
|
34
|
+
res,
|
|
35
|
+
"oauth-authorization.manage",
|
|
36
|
+
`Only the lead can start the ${providerName} OAuth flow.`,
|
|
37
|
+
agentId,
|
|
38
|
+
);
|
|
39
|
+
if (!allowed) return null;
|
|
40
|
+
return { userId: await resolveHttpAuditUserId(req, agentId) };
|
|
41
|
+
}
|
|
@@ -15,6 +15,11 @@ import { forceRefreshAuthorizationOrThrow } from "../../oauth/ensure-token";
|
|
|
15
15
|
import { completeGenericOAuthCallback } from "../oauth-callback";
|
|
16
16
|
import { route } from "../route-def";
|
|
17
17
|
import { allowedCredentialRedirect, deriveApiBaseUrl, parseQueryParams } from "../utils";
|
|
18
|
+
import {
|
|
19
|
+
ensureTrackerAuthorizeAdmin,
|
|
20
|
+
TrackerAuthorizeQuerySchema,
|
|
21
|
+
TrackerAuthorizeUrlSchema,
|
|
22
|
+
} from "./authorize-gate";
|
|
18
23
|
|
|
19
24
|
const MANUAL_WEBHOOK_INSTRUCTIONS =
|
|
20
25
|
"See docs-site/.../integrations/jira.mdx for manual webhook registration steps.";
|
|
@@ -80,12 +85,20 @@ const jiraAuthorize = route({
|
|
|
80
85
|
method: "get",
|
|
81
86
|
path: "/api/trackers/jira/authorize",
|
|
82
87
|
pattern: ["api", "trackers", "jira", "authorize"],
|
|
83
|
-
summary: "
|
|
88
|
+
summary: "Start the Jira OAuth flow (admin): redirect to the consent screen, or return its URL",
|
|
84
89
|
tags: ["Trackers"],
|
|
85
|
-
|
|
86
|
-
|
|
90
|
+
// Bearer-required (route default) and gated on oauth-authorization.manage:
|
|
91
|
+
// the grant lands on the swarm-wide default authorization. Only the
|
|
92
|
+
// provider callback below stays public.
|
|
93
|
+
query: TrackerAuthorizeQuerySchema,
|
|
94
|
+
rbac: { permission: "oauth-authorization.manage" },
|
|
87
95
|
responses: {
|
|
96
|
+
200: {
|
|
97
|
+
description: "Consent URL (format=json), for clients that navigate themselves",
|
|
98
|
+
schema: TrackerAuthorizeUrlSchema,
|
|
99
|
+
},
|
|
88
100
|
302: { description: "Redirect to Atlassian OAuth" },
|
|
101
|
+
403: { description: "Caller lacks oauth-authorization.manage" },
|
|
89
102
|
500: { description: "Failed to generate authorization URL" },
|
|
90
103
|
503: { description: "Jira integration not configured" },
|
|
91
104
|
},
|
|
@@ -273,6 +286,8 @@ export async function handleJiraTracker(
|
|
|
273
286
|
const queryParams = parseQueryParams(req.url || "");
|
|
274
287
|
const parsed = await jiraAuthorize.parse(req, res, pathSegments, queryParams);
|
|
275
288
|
if (!parsed) return true;
|
|
289
|
+
const initiator = await ensureTrackerAuthorizeAdmin(req, res, "Jira");
|
|
290
|
+
if (!initiator) return true;
|
|
276
291
|
if (!isJiraEnabled()) {
|
|
277
292
|
res.writeHead(503, { "Content-Type": "application/json" });
|
|
278
293
|
res.end(JSON.stringify({ error: "Jira integration not configured" }));
|
|
@@ -280,13 +295,20 @@ export async function handleJiraTracker(
|
|
|
280
295
|
}
|
|
281
296
|
|
|
282
297
|
try {
|
|
283
|
-
const url = await getJiraAuthorizationUrl(
|
|
298
|
+
const url = await getJiraAuthorizationUrl(
|
|
299
|
+
allowedCredentialRedirect(parsed.query.redirect),
|
|
300
|
+
initiator.userId,
|
|
301
|
+
);
|
|
284
302
|
if (!url) {
|
|
285
303
|
res.writeHead(500, { "Content-Type": "application/json" });
|
|
286
304
|
res.end(JSON.stringify({ error: "Failed to generate authorization URL" }));
|
|
287
305
|
return true;
|
|
288
306
|
}
|
|
289
307
|
|
|
308
|
+
if (parsed.query.format === "json") {
|
|
309
|
+
jiraAuthorize.respond(res, 200, { authorizeUrl: url });
|
|
310
|
+
return true;
|
|
311
|
+
}
|
|
290
312
|
res.writeHead(302, { Location: url });
|
|
291
313
|
res.end();
|
|
292
314
|
} catch (err) {
|
|
@@ -13,6 +13,11 @@ import { forceRefreshAuthorizationOrThrow } from "../../oauth/ensure-token";
|
|
|
13
13
|
import { completeGenericOAuthCallback } from "../oauth-callback";
|
|
14
14
|
import { route } from "../route-def";
|
|
15
15
|
import { allowedCredentialRedirect, deriveApiBaseUrl, parseQueryParams } from "../utils";
|
|
16
|
+
import {
|
|
17
|
+
ensureTrackerAuthorizeAdmin,
|
|
18
|
+
TrackerAuthorizeQuerySchema,
|
|
19
|
+
TrackerAuthorizeUrlSchema,
|
|
20
|
+
} from "./authorize-gate";
|
|
16
21
|
|
|
17
22
|
// ─── Schemas ─────────────────────────────────────────────────────────────────
|
|
18
23
|
|
|
@@ -42,12 +47,20 @@ const linearAuthorize = route({
|
|
|
42
47
|
method: "get",
|
|
43
48
|
path: "/api/trackers/linear/authorize",
|
|
44
49
|
pattern: ["api", "trackers", "linear", "authorize"],
|
|
45
|
-
summary: "
|
|
50
|
+
summary: "Start the Linear OAuth flow (admin): redirect to the consent screen, or return its URL",
|
|
46
51
|
tags: ["Trackers"],
|
|
47
|
-
|
|
48
|
-
|
|
52
|
+
// Bearer-required (route default) and gated on oauth-authorization.manage:
|
|
53
|
+
// the grant lands on the swarm-wide default authorization. Only the
|
|
54
|
+
// provider callback below stays public.
|
|
55
|
+
query: TrackerAuthorizeQuerySchema,
|
|
56
|
+
rbac: { permission: "oauth-authorization.manage" },
|
|
49
57
|
responses: {
|
|
58
|
+
200: {
|
|
59
|
+
description: "Consent URL (format=json), for clients that navigate themselves",
|
|
60
|
+
schema: TrackerAuthorizeUrlSchema,
|
|
61
|
+
},
|
|
50
62
|
302: { description: "Redirect to Linear OAuth" },
|
|
63
|
+
403: { description: "Caller lacks oauth-authorization.manage" },
|
|
51
64
|
500: { description: "Failed to generate authorization URL" },
|
|
52
65
|
503: { description: "Linear integration not configured" },
|
|
53
66
|
},
|
|
@@ -164,6 +177,8 @@ export async function handleLinearTracker(
|
|
|
164
177
|
const queryParams = parseQueryParams(req.url || "");
|
|
165
178
|
const parsed = await linearAuthorize.parse(req, res, pathSegments, queryParams);
|
|
166
179
|
if (!parsed) return true;
|
|
180
|
+
const initiator = await ensureTrackerAuthorizeAdmin(req, res, "Linear");
|
|
181
|
+
if (!initiator) return true;
|
|
167
182
|
if (!isLinearEnabled()) {
|
|
168
183
|
res.writeHead(503, { "Content-Type": "application/json" });
|
|
169
184
|
res.end(JSON.stringify({ error: "Linear integration not configured" }));
|
|
@@ -171,13 +186,20 @@ export async function handleLinearTracker(
|
|
|
171
186
|
}
|
|
172
187
|
|
|
173
188
|
try {
|
|
174
|
-
const url = await getLinearAuthorizationUrl(
|
|
189
|
+
const url = await getLinearAuthorizationUrl(
|
|
190
|
+
allowedCredentialRedirect(parsed.query.redirect),
|
|
191
|
+
initiator.userId,
|
|
192
|
+
);
|
|
175
193
|
if (!url) {
|
|
176
194
|
res.writeHead(500, { "Content-Type": "application/json" });
|
|
177
195
|
res.end(JSON.stringify({ error: "Failed to generate authorization URL" }));
|
|
178
196
|
return true;
|
|
179
197
|
}
|
|
180
198
|
|
|
199
|
+
if (parsed.query.format === "json") {
|
|
200
|
+
linearAuthorize.respond(res, 200, { authorizeUrl: url });
|
|
201
|
+
return true;
|
|
202
|
+
}
|
|
181
203
|
res.writeHead(302, { Location: url });
|
|
182
204
|
res.end();
|
|
183
205
|
} catch (err) {
|
|
@@ -62,7 +62,12 @@ export function splitChatMessage(text: string, limit: number): string[] {
|
|
|
62
62
|
cut = limit;
|
|
63
63
|
// Never split a surrogate pair (emoji and other astral characters).
|
|
64
64
|
const code = rest.charCodeAt(cut - 1);
|
|
65
|
-
if (code >= 0xd800 && code <= 0xdbff)
|
|
65
|
+
if (code >= 0xd800 && code <= 0xdbff) {
|
|
66
|
+
// A limit smaller than one code point cannot honor both "within the
|
|
67
|
+
// limit" and "no split pairs"; keep the pair whole so the cut still
|
|
68
|
+
// advances (cut would otherwise become 0 and loop forever).
|
|
69
|
+
cut = cut > 1 ? cut - 1 : cut + 1;
|
|
70
|
+
}
|
|
66
71
|
}
|
|
67
72
|
chunks.push(rest.slice(0, cut).trimEnd());
|
|
68
73
|
rest = rest.slice(cut).replace(/^[\n ]+/, "");
|
package/src/jira/oauth.ts
CHANGED
|
@@ -19,7 +19,10 @@ export async function getJiraOAuthConfig(): Promise<OAuthProviderConfig | null>
|
|
|
19
19
|
return app ? oauthAppRowToProviderConfig(app) : null;
|
|
20
20
|
}
|
|
21
21
|
|
|
22
|
-
export async function getJiraAuthorizationUrl(
|
|
22
|
+
export async function getJiraAuthorizationUrl(
|
|
23
|
+
finalRedirect?: string,
|
|
24
|
+
userId?: string | null,
|
|
25
|
+
): Promise<string | null> {
|
|
23
26
|
const config = await getJiraOAuthConfig();
|
|
24
27
|
if (!config) return null;
|
|
25
28
|
// flow='tracker' so the unified state-keyed callback runs the tracker
|
|
@@ -29,6 +32,9 @@ export async function getJiraAuthorizationUrl(finalRedirect?: string): Promise<s
|
|
|
29
32
|
flow: "tracker",
|
|
30
33
|
label: "default",
|
|
31
34
|
...(finalRedirect ? { finalRedirect } : {}),
|
|
35
|
+
// The initiating user, recorded on the pending row and then on the
|
|
36
|
+
// authorization (connectedByUserId), same as the generic authorize-url route.
|
|
37
|
+
...(userId ? { userId } : {}),
|
|
32
38
|
});
|
|
33
39
|
return result.url;
|
|
34
40
|
}
|