@desplega.ai/agent-swarm 2.8.1 → 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.
Files changed (194) hide show
  1. package/dist/{acp-adapter-pdy3qsvg.js → acp-adapter-fqzkxyra.js} +3 -3
  2. package/dist/{actions-pwjpn0j6.js → actions-kxek041g.js} +17 -17
  3. package/dist/{amp-adapter-cq9jgj6x.js → amp-adapter-ce7jjke4.js} +1 -1
  4. package/dist/{app-cnfffgwg.js → app-v6zz8yh0.js} +3 -3
  5. package/dist/{assistant-kpn317y1.js → assistant-m0sw9xx2.js} +18 -18
  6. package/dist/{boot-args-schema-pbbnhmc3.js → boot-args-schema-66bk37wv.js} +1 -1
  7. package/dist/{boot-reembed-9m0ysxma.js → boot-reembed-edjpwsc1.js} +1 -1
  8. package/dist/{boot-reembed-majbn53m.js → boot-reembed-y27n09tz.js} +1 -1
  9. package/dist/{boot-scrub-sweep-app8g8ym.js → boot-scrub-sweep-1xc35965.js} +3 -3
  10. package/dist/{boot-seeds-pbtmvcjm.js → boot-seeds-7hjj91qj.js} +4 -4
  11. package/dist/{boxd-qbkxy6ap.js → boxd-ent8ch04.js} +1 -1
  12. package/dist/{claude-adapter-wn1g3qp5.js → claude-adapter-stw7jdcf.js} +3 -3
  13. package/dist/{claude-managed-setup-pd47nzch.js → claude-managed-setup-y6z2perp.js} +1 -1
  14. package/dist/{claude-sdk-session-3a2a6589.js → claude-sdk-session-vvya8wqk.js} +3 -3
  15. package/dist/{cli-wk18cm92.js → cli-0cq8y6m7.js} +1 -1
  16. package/dist/{cli-p1w18yhx.js → cli-1pz0330a.js} +1 -1
  17. package/dist/{cli-d3p5vwbk.js → cli-1qkz151v.js} +3 -3
  18. package/dist/{cli-89cqnasv.js → cli-26ctbcdp.js} +18 -6
  19. package/dist/{cli-syybb0p1.js → cli-2kvhc7x8.js} +7 -7
  20. package/dist/{cli-93k32c37.js → cli-3e875j5p.js} +128 -41
  21. package/dist/{cli-k0615eh8.js → cli-3sy2xags.js} +10 -10
  22. package/dist/{cli-dy32zecz.js → cli-3vmb0n58.js} +1 -1
  23. package/dist/{cli-4r05hnqa.js → cli-4vzgeta4.js} +13 -13
  24. package/dist/{cli-b5rs97a6.js → cli-5y340nzn.js} +4 -4
  25. package/dist/{cli-7p1kvkck.js → cli-6rc5frdm.js} +1 -1
  26. package/dist/{cli-jcpr5smb.js → cli-837vfs2x.js} +2 -2
  27. package/dist/{cli-b085njxz.js → cli-959kp5h2.js} +12 -11
  28. package/dist/{cli-k93bq1wq.js → cli-97ae65rz.js} +4 -4
  29. package/dist/{cli-m4dqmnbp.js → cli-9mb2q6pb.js} +1 -1
  30. package/dist/{cli-bb431xey.js → cli-a0z912j7.js} +121 -33
  31. package/dist/{cli-k26bkr9t.js → cli-b98a65ed.js} +3 -3
  32. package/dist/{cli-k0wwfqbg.js → cli-dns0y538.js} +4 -0
  33. package/dist/{cli-tk7cjj8h.js → cli-dzpc6en0.js} +1 -1
  34. package/dist/{cli-6mma83xa.js → cli-e1p3n5gq.js} +4 -4
  35. package/dist/{cli-re4raaj0.js → cli-f4e8r23x.js} +1 -1
  36. package/dist/{cli-qmqk2yc2.js → cli-f4r3g076.js} +1 -1
  37. package/dist/{cli-pcad4cb1.js → cli-f6bahpn5.js} +1 -1
  38. package/dist/{cli-b8e9nb04.js → cli-fpjmegdb.js} +1 -1
  39. package/dist/{cli-0ntbxyaa.js → cli-fwy8kfd6.js} +271 -37
  40. package/dist/{cli-tacge1w0.js → cli-g5mtmf6t.js} +6 -6
  41. package/dist/{cli-sn7rtnj4.js → cli-gyt3zydq.js} +3 -3
  42. package/dist/{cli-vbh10fqa.js → cli-j24zbska.js} +3 -3
  43. package/dist/{cli-vqptjbr7.js → cli-jdknh18m.js} +10 -10
  44. package/dist/{cli-7b8sbmag.js → cli-kjtwrhea.js} +1 -1
  45. package/dist/{cli-9vhebtjz.js → cli-mxn1qvbn.js} +3 -2
  46. package/dist/{cli-zcsw143p.js → cli-n6vtrcht.js} +1 -1
  47. package/dist/{cli-2zp0et3v.js → cli-pchypa1s.js} +55 -19
  48. package/dist/{cli-gax7fk3t.js → cli-pfs8adn4.js} +1 -1
  49. package/dist/{cli-1xh9a7hn.js → cli-q24n86d2.js} +2 -2
  50. package/dist/{cli-7w69ne2f.js → cli-rcecc3yq.js} +167 -43
  51. package/dist/{cli-xae4g51r.js → cli-rh15cakt.js} +1 -1
  52. package/dist/{cli-yn2bbre9.js → cli-rmzsadkf.js} +1 -1
  53. package/dist/{cli-a3b239vq.js → cli-t2tma8gb.js} +1 -1
  54. package/dist/{cli-9wngrawf.js → cli-tekytdq9.js} +2 -2
  55. package/dist/{cli-tqegb8eq.js → cli-vdektqgf.js} +1 -1
  56. package/dist/{cli-cyhbbd1z.js → cli-w401b9tq.js} +1 -1
  57. package/dist/{cli-jywyhqws.js → cli-xf3qw745.js} +3 -3
  58. package/dist/{cli-hxpyc9sn.js → cli-z1w943va.js} +2 -2
  59. package/dist/{cli-yncmerje.js → cli-zh9rsbqf.js} +2 -2
  60. package/dist/cli.js +16 -16
  61. package/dist/{codex-adapter-nha71q3n.js → codex-adapter-zerf5qsp.js} +1 -1
  62. package/dist/{codex-hook-h3vk6xzr.js → codex-hook-30gyhzxe.js} +1 -1
  63. package/dist/{codex-session-runner-ak9x1k1h.js → codex-session-runner-89s304py.js} +1 -1
  64. package/dist/{commands-f587qpq8.js → commands-jeh1b51j.js} +3 -3
  65. package/dist/{controller-hxx8wwy1.js → controller-mctfbrse.js} +3 -3
  66. package/dist/{controllers-connect-k5sg9m9h.js → controllers-connect-nxa1ddwn.js} +18 -18
  67. package/dist/{cursor-adapter-n5nc3mfe.js → cursor-adapter-qj8vehv6.js} +1 -1
  68. package/dist/{db-nzf8zb5z.js → db-2dvay0es.js} +3 -3
  69. package/dist/{db-amm8w15a.js → db-b36qn6k3.js} +2 -2
  70. package/dist/{dispatcher-89zrts8f.js → dispatcher-gndbta01.js} +16 -16
  71. package/dist/{dsh-adapter-nrhbrjz8.js → dsh-adapter-f75sz821.js} +1 -1
  72. package/dist/{e2b-jkwfhbcv.js → e2b-3gpc2n3w.js} +1 -1
  73. package/dist/{e2b-s16txnpx.js → e2b-jbm7mj93.js} +1 -1
  74. package/dist/{embedding-space-ezwenjmj.js → embedding-space-4p05vb2x.js} +6 -6
  75. package/dist/{embeddings-np74ht6g.js → embeddings-m6768mgh.js} +1 -1
  76. package/dist/{external-channel-z46yx9d7.js → external-channel-gjv3jne3.js} +2 -2
  77. package/dist/{fx-adapter-3q12snn6.js → fx-adapter-rpsgb1tw.js} +4 -4
  78. package/dist/{grok-adapter-ahb1w033.js → grok-adapter-n2m3zjg1.js} +4 -4
  79. package/dist/handlers-nv8edn19.js +32 -0
  80. package/dist/{heartbeat-dt9qw9c8.js → heartbeat-a1tv60gt.js} +19 -19
  81. package/dist/{hook-8k6fbz9b.js → hook-8h5dzcgq.js} +2 -2
  82. package/dist/{hook-jgcgygex.js → hook-cyaps9ba.js} +4 -4
  83. package/dist/{http-haw4r8ne.js → http-t15mhbd9.js} +1731 -77
  84. package/dist/{index-s4ewdma4.js → index-ksmyd6kc.js} +16 -16
  85. package/dist/{index-tez78qj3.js → index-qav6455f.js} +13 -11
  86. package/dist/index-rjnrje98.js +32 -0
  87. package/dist/index-tv3413wy.js +33 -0
  88. package/dist/{index-5gk12my8.js → index-w1zqf680.js} +1 -1
  89. package/dist/{keepalive-xn6s7rmg.js → keepalive-91s7hzrb.js} +3 -3
  90. package/dist/{lead-6ygbfhbh.js → lead-3hmddvrm.js} +30 -30
  91. package/dist/{maintenance-vdts800b.js → maintenance-7pjmy5xy.js} +1 -1
  92. package/dist/{oauth-refresh-sweep-094c8wfk.js → oauth-refresh-sweep-rzqfm94j.js} +2 -2
  93. package/dist/{onboard-v99eh56m.js → onboard-74st7pag.js} +3 -3
  94. package/dist/{opencode-adapter-dsagkhtw.js → opencode-adapter-arn7gm8q.js} +2 -2
  95. package/dist/{otel-impl-q7yr9yp0.js → otel-impl-rnzey8cb.js} +1 -1
  96. package/dist/{pi-mono-adapter-546cd1cc.js → pi-mono-adapter-6mkwq64n.js} +3 -2
  97. package/dist/{pricing-refresh-7dh2yase.js → pricing-refresh-ha21jhk7.js} +2 -2
  98. package/dist/{rbac-roles-npbmdh77.js → rbac-roles-59dxachk.js} +2 -2
  99. package/dist/{rbac-roles-mdmc96p4.js → rbac-roles-wqhma4dr.js} +3 -3
  100. package/dist/{render-v2-twhhwmms.js → render-v2-14kpzx12.js} +3 -3
  101. package/dist/{resume-5gsrjd5e.js → resume-gsa5fb5f.js} +6 -6
  102. package/dist/{session-access-m191x30x.js → session-access-skm7bnp6.js} +4 -4
  103. package/dist/{session-source-backfill-nt923ask.js → session-source-backfill-pbqzbncv.js} +2 -2
  104. package/dist/{setup-wv467afy.js → setup-5yermsem.js} +1 -1
  105. package/dist/{work-objects-8zkrpy13.js → work-objects-xj0ck0w4.js} +19 -19
  106. package/dist/{worker-follow-up-cecqszem.js → worker-follow-up-911xc0b8.js} +18 -16
  107. package/dist/{worker-mz5z7kj0.js → worker-qgg0m2gw.js} +30 -30
  108. package/openapi.json +1741 -290
  109. package/package.json +2 -2
  110. package/src/apps/catalog.generated.json +120 -1
  111. package/src/apps/definition.ts +38 -11
  112. package/src/apps/page-validator.ts +88 -0
  113. package/src/be/db/model-profiles.ts +110 -11
  114. package/src/be/db/tasks/read.ts +20 -0
  115. package/src/be/db/workflow-run-definitions.ts +19 -8
  116. package/src/be/db-client.ts +43 -5
  117. package/src/be/db.ts +9 -3
  118. package/src/be/migrations/284_model_profile_fallbacks.sql +9 -0
  119. package/src/be/model-profile-check.ts +43 -18
  120. package/src/be/runtime-pools/routing.ts +1 -0
  121. package/src/be/savings/calibrate.ts +468 -0
  122. package/src/be/savings/compute.ts +182 -0
  123. package/src/be/savings/model.ts +406 -0
  124. package/src/be/scripts/typecheck.ts +5 -0
  125. package/src/be/seed/agent-fs-provision.ts +48 -11
  126. package/src/be/seed/workflows-seeder.ts +67 -23
  127. package/src/be/skill-parser.ts +19 -7
  128. package/src/commands/onboard/agent-fs-version.ts +1 -1
  129. package/src/commands/provider-error-class.ts +97 -0
  130. package/src/commands/runner.ts +99 -17
  131. package/src/extensions/contract-types.generated.ts +1 -1
  132. package/src/http/all-routes.ts +2 -0
  133. package/src/http/fs.ts +8 -2
  134. package/src/http/index.ts +4 -0
  135. package/src/http/model-profiles.ts +43 -10
  136. package/src/http/poll.ts +1 -0
  137. package/src/http/savings-calibration.ts +277 -0
  138. package/src/http/savings.ts +363 -0
  139. package/src/http/tasks.ts +46 -4
  140. package/src/http/trackers/authorize-gate.ts +41 -0
  141. package/src/http/trackers/jira.ts +26 -4
  142. package/src/http/trackers/linear.ts +26 -4
  143. package/src/integrations/chat-sdk/limits.ts +6 -1
  144. package/src/jira/oauth.ts +7 -1
  145. package/src/linear/README.md +2 -1
  146. package/src/linear/oauth.ts +7 -1
  147. package/src/providers/amp-adapter.ts +1 -1
  148. package/src/providers/codex-adapter.ts +3 -0
  149. package/src/providers/pi-mono-adapter.ts +6 -5
  150. package/src/providers/types.ts +7 -0
  151. package/src/scripts-runtime/sdk-allowlist.ts +11 -1
  152. package/src/scripts-runtime/swarm-sdk.ts +6 -0
  153. package/src/scripts-runtime/types/stdlib.d.ts +9 -0
  154. package/src/scripts-runtime/types/swarm-extension.d.ts +34 -0
  155. package/src/scripts-runtime/types/swarm-sdk.d.ts +9 -0
  156. package/src/tasks/worker-follow-up.ts +142 -3
  157. package/src/tests/agent-fs-provision-seeder.test.ts +81 -0
  158. package/src/tests/apps-chart-shell.test.ts +170 -0
  159. package/src/tests/apps-icon.test.ts +156 -2
  160. package/src/tests/chat-sdk-relay.test.ts +12 -0
  161. package/src/tests/codex-adapter.test.ts +11 -0
  162. package/src/tests/comb-default.test.ts +6 -0
  163. package/src/tests/core-auth.test.ts +7 -6
  164. package/src/tests/db-client-busy-retry.test.ts +58 -6
  165. package/src/tests/deploy-guard.test.ts +154 -0
  166. package/src/tests/docs-index-footprint.test.js +3 -3
  167. package/src/tests/fixtures/app-shell-charts-definition.json.txt +180 -0
  168. package/src/tests/model-profile-fallbacks.test.ts +482 -0
  169. package/src/tests/model-profiles-api.test.ts +1 -0
  170. package/src/tests/pi-mono-session-cost-on-abort.test.ts +115 -0
  171. package/src/tests/provider-error-class.test.ts +174 -0
  172. package/src/tests/runner-provider-fallback.test.ts +197 -0
  173. package/src/tests/savings-calibration-api.test.ts +264 -0
  174. package/src/tests/savings-calibration.test.ts +201 -0
  175. package/src/tests/savings-compute.test.ts +406 -0
  176. package/src/tests/savings-model.test.ts +287 -0
  177. package/src/tests/script-connections.test.ts +2 -0
  178. package/src/tests/sdk-allowlist.test.ts +40 -0
  179. package/src/tests/seed-workflows.test.ts +167 -11
  180. package/src/tests/skill-parser.test.ts +45 -0
  181. package/src/tests/tracker-oauth-authorize-auth.test.ts +262 -0
  182. package/src/tests/workflow-definition-pinning.test.ts +128 -3
  183. package/src/tests/workflow-script-principal.test.ts +94 -4
  184. package/src/tools/app-upsert.ts +1 -1
  185. package/src/tools/model-profiles/list-model-profiles.ts +4 -2
  186. package/src/tools/update-profile.ts +1 -1
  187. package/src/types.ts +115 -33
  188. package/src/utils/constants.ts +2 -0
  189. package/templates/skills/apps/SKILL.md +62 -3
  190. package/templates/skills/apps/content.md +62 -3
  191. package/templates/skills/swarm-docs/content.md +2 -0
  192. package/dist/handlers-vbww69re.js +0 -32
  193. package/dist/index-4xwaf5th.js +0 -32
  194. package/dist/index-f0hcrs8e.js +0 -33
@@ -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 { createResumeFollowUp, createWorkerTaskFollowUp } from "../tasks/worker-follow-up";
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.object({ reason: ResumeReasonSchema }),
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: "Redirect to Atlassian OAuth consent screen",
88
+ summary: "Start the Jira OAuth flow (admin): redirect to the consent screen, or return its URL",
84
89
  tags: ["Trackers"],
85
- auth: { apiKey: false },
86
- query: z.object({ redirect: z.string().optional() }),
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(allowedCredentialRedirect(parsed.query.redirect));
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: "Redirect to Linear OAuth consent screen",
50
+ summary: "Start the Linear OAuth flow (admin): redirect to the consent screen, or return its URL",
46
51
  tags: ["Trackers"],
47
- auth: { apiKey: false },
48
- query: z.object({ redirect: z.string().optional() }),
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(allowedCredentialRedirect(parsed.query.redirect));
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) cut -= 1;
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(finalRedirect?: string): Promise<string | null> {
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
  }