pi-dev-flow 0.100.1 → 0.101.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +16 -0
- package/README.md +2 -2
- package/docs/jira.md +9 -7
- package/extensions/dev-flow.ts +14 -29
- package/package.json +1 -1
- package/src/core.ts +4 -0
- package/src/jira/client.ts +115 -232
- package/src/jira/creds.ts +14 -34
- package/src/jira/mcp.ts +63 -16
- package/src/jira/sync.ts +2 -1
- package/src/planhtml.ts +209 -0
- package/src/runtime/jira.ts +120 -38
- package/src/runtime/planpdf.ts +85 -0
package/src/jira/client.ts
CHANGED
|
@@ -1,23 +1,22 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Jira operations over the official Atlassian Rovo MCP server (src/jira/mcp.ts)
|
|
3
|
-
*
|
|
4
|
-
*
|
|
2
|
+
* Jira operations over the official Atlassian Rovo MCP server (src/jira/mcp.ts) — dev-flow's only path to
|
|
3
|
+
* Jira. A scoped API token works there and nowhere else (Jira's REST API refuses it), so there is no REST
|
|
4
|
+
* fallback: one path, retried on transient failures, with errors that name the fix.
|
|
5
5
|
*
|
|
6
|
-
* Tool names and argument names are resolved against the server's live `tools/list`:
|
|
7
|
-
*
|
|
8
|
-
* published as schemas, so each operation names its candidates and the first one offered wins.
|
|
6
|
+
* Tool names and argument names are resolved against the server's live `tools/list`: the argument spellings
|
|
7
|
+
* are only published as schemas, so each operation names its candidates and the first one offered wins.
|
|
9
8
|
*
|
|
10
9
|
* Every operation returns a JiraResult — it never throws into a gate.
|
|
11
10
|
*/
|
|
12
11
|
import { readFileSync } from "node:fs";
|
|
13
12
|
import path from "node:path";
|
|
14
|
-
import {
|
|
15
|
-
import { type FetchLike, McpClient, type McpTool, resultText, resultValue } from "./mcp.ts";
|
|
13
|
+
import { bearer, type JiraCreds } from "./creds.ts";
|
|
14
|
+
import { type FetchLike, McpClient, type McpOptions, type McpTool, resultText, resultValue } from "./mcp.ts";
|
|
16
15
|
import type { StatusInfo } from "./config.ts";
|
|
17
16
|
|
|
18
17
|
export const MCP_URL = process.env.JIRA_MCP_URL ?? "https://mcp.atlassian.com/v2/mcp?tools=all";
|
|
19
18
|
|
|
20
|
-
export type JiraResult<T> = { ok: true; value: T
|
|
19
|
+
export type JiraResult<T> = { ok: true; value: T } | { ok: false; error: string };
|
|
21
20
|
|
|
22
21
|
export interface JiraUser {
|
|
23
22
|
accountId: string;
|
|
@@ -54,11 +53,27 @@ const TOOLS = {
|
|
|
54
53
|
upload: ["uploadAttachmentToJiraIssue"],
|
|
55
54
|
transitions: ["listJiraIssueTransitions", "getTransitionsForJiraIssue"],
|
|
56
55
|
transition: ["transitionJiraIssue"],
|
|
57
|
-
search: ["searchJiraIssuesUsingJql"],
|
|
58
56
|
create: ["createJiraIssue"],
|
|
59
57
|
} as const;
|
|
60
58
|
type Op = keyof typeof TOOLS;
|
|
61
59
|
|
|
60
|
+
/** Ops that change nothing: a lost answer may be asked for again. The rest (comment, upload, transition,
|
|
61
|
+
* create) are retried only when the server said it did not run them. */
|
|
62
|
+
const READ_OPS: ReadonlySet<Op> = new Set<Op>(["me", "resources", "projects", "issueTypes", "statuses", "issue", "comments", "transitions"]);
|
|
63
|
+
|
|
64
|
+
const COMMENTS_PAGE = 20; // the server's cap per page
|
|
65
|
+
const COMMENTS_MAX = 100;
|
|
66
|
+
|
|
67
|
+
const missingTool = (op: Op) =>
|
|
68
|
+
`the Atlassian MCP server offers this token no ${TOOLS[op].join("/")} tool — the token needs the ${READ_OPS.has(op) ? "read" : "write"}:jira:agent-interface scope`;
|
|
69
|
+
|
|
70
|
+
/** Add the fix to the known MCP failures. */
|
|
71
|
+
function explain(msg: string): string {
|
|
72
|
+
if (/isn't explicitly granted|not explicitly granted/i.test(msg))
|
|
73
|
+
return `${msg} — the token cannot reach this site: it must be a scoped API token (read:jira:agent-interface, write:jira:agent-interface) of an account on it; the operator re-runs /flow jira login`;
|
|
74
|
+
return msg;
|
|
75
|
+
}
|
|
76
|
+
|
|
62
77
|
// logical argument → candidate schema property names
|
|
63
78
|
const ARGS: Record<string, string[]> = {
|
|
64
79
|
cloudId: ["cloudId"],
|
|
@@ -76,12 +91,10 @@ const ARGS: Record<string, string[]> = {
|
|
|
76
91
|
mode: ["mode"],
|
|
77
92
|
view: ["view"],
|
|
78
93
|
order: ["orderBy"],
|
|
79
|
-
|
|
80
|
-
|
|
94
|
+
startAt: ["startAt"],
|
|
95
|
+
// v2 uploads take a local filePath and hand back an Atlassian Media request, then the media fileId
|
|
81
96
|
filePath: ["filePath"],
|
|
82
97
|
fileId: ["fileId"],
|
|
83
|
-
filename: ["filename", "fileName", "name"],
|
|
84
|
-
mime: ["mimeType", "contentType"],
|
|
85
98
|
};
|
|
86
99
|
|
|
87
100
|
const str = (v: unknown) => (typeof v === "string" ? v : v == null ? "" : String(v));
|
|
@@ -133,99 +146,22 @@ export function adfText(node: unknown): string {
|
|
|
133
146
|
return /^(paragraph|heading|listItem|codeBlock|blockquote|bulletList|orderedList|rule)$/.test(str(n.type)) ? `${kids}\n` : kids;
|
|
134
147
|
}
|
|
135
148
|
|
|
136
|
-
/** Markdown-ish text → a minimal ADF document (paragraphs and code blocks) — for REST, which takes no markdown. */
|
|
137
|
-
export function toAdf(text: string): unknown {
|
|
138
|
-
const content: unknown[] = [];
|
|
139
|
-
const parts = text.split(/```[^\n]*\n([\s\S]*?)```/);
|
|
140
|
-
parts.forEach((part, i) => {
|
|
141
|
-
if (i % 2 === 1) return void content.push({ type: "codeBlock", content: part ? [{ type: "text", text: part.replace(/\n$/, "") }] : [] });
|
|
142
|
-
for (const para of part.split(/\n{2,}/)) {
|
|
143
|
-
const lines = para.split("\n").filter((l, j, a) => l || j < a.length - 1);
|
|
144
|
-
if (!lines.join("").trim()) continue;
|
|
145
|
-
const inl: unknown[] = [];
|
|
146
|
-
lines.forEach((l, j) => {
|
|
147
|
-
if (j) inl.push({ type: "hardBreak" });
|
|
148
|
-
if (l) inl.push({ type: "text", text: l });
|
|
149
|
-
});
|
|
150
|
-
content.push({ type: "paragraph", content: inl });
|
|
151
|
-
}
|
|
152
|
-
});
|
|
153
|
-
return { type: "doc", version: 1, content };
|
|
154
|
-
}
|
|
155
149
|
|
|
156
150
|
const MIME: Record<string, string> = { ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".gif": "image/gif", ".webp": "image/webp", ".md": "text/markdown", ".txt": "text/plain", ".json": "application/json", ".pdf": "application/pdf" };
|
|
157
151
|
export const mimeOf = (file: string) => MIME[path.extname(file).toLowerCase()] ?? "application/octet-stream";
|
|
158
152
|
|
|
159
153
|
export class JiraClient {
|
|
160
154
|
readonly creds: JiraCreds;
|
|
161
|
-
|
|
162
|
-
private mcpP: Promise<McpClient> | undefined;
|
|
163
|
-
/** the MCP auth scheme in use, once picked; `verified` when the site was seen through it */
|
|
164
|
-
private picked: { scheme: JiraAuth; verified: boolean } | undefined;
|
|
155
|
+
readonly mcp: McpClient;
|
|
165
156
|
private readonly fetchFn: FetchLike;
|
|
166
157
|
private cloudIdP: Promise<string> | undefined;
|
|
167
158
|
private cloudIdFixed: string | undefined;
|
|
168
|
-
/** the REST base a scoped token needs, once the site URL refused it */
|
|
169
|
-
private gateway: string | undefined;
|
|
170
159
|
|
|
171
|
-
constructor(creds: JiraCreds, opts: { cloudId?: string; fetch?: FetchLike; mcpUrl?: string } = {}) {
|
|
160
|
+
constructor(creds: JiraCreds, opts: { cloudId?: string; fetch?: FetchLike; mcpUrl?: string; mcp?: McpOptions } = {}) {
|
|
172
161
|
this.creds = creds;
|
|
173
162
|
this.fetchFn = opts.fetch ?? (globalThis.fetch as unknown as FetchLike);
|
|
174
163
|
this.cloudIdFixed = opts.cloudId;
|
|
175
|
-
this.
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
/** The MCP session, with the auth scheme picked on first use. */
|
|
179
|
-
private mcp(): Promise<McpClient> {
|
|
180
|
-
this.mcpP ??= this.pickAuth().catch((e) => {
|
|
181
|
-
this.mcpP = undefined;
|
|
182
|
-
throw e;
|
|
183
|
-
});
|
|
184
|
-
return this.mcpP;
|
|
185
|
-
}
|
|
186
|
-
|
|
187
|
-
/** Which Authorization the MCP server honours for this token. A scoped token works only as Bearer; sent as
|
|
188
|
-
* Basic the server still lists its tools but sees no site ("Cloud id … isn't explicitly granted"). So each
|
|
189
|
-
* scheme is tried until getAccessibleAtlassianResources returns a site; a stored scheme is used as is. */
|
|
190
|
-
private async pickAuth(): Promise<McpClient> {
|
|
191
|
-
const make = (s: JiraAuth) => new McpClient(this.mcpUrl, { authorization: mcpAuth(this.creds, s) }, this.fetchFn);
|
|
192
|
-
if (this.creds.auth) {
|
|
193
|
-
this.picked = { scheme: this.creds.auth, verified: false };
|
|
194
|
-
return make(this.creds.auth);
|
|
195
|
-
}
|
|
196
|
-
let fallback: { c: McpClient; scheme: JiraAuth } | undefined;
|
|
197
|
-
let err: unknown;
|
|
198
|
-
for (const scheme of ["bearer", "basic"] as const) {
|
|
199
|
-
const c = make(scheme);
|
|
200
|
-
try {
|
|
201
|
-
const tools = await c.listTools();
|
|
202
|
-
const t = tools.find((x) => (TOOLS.resources as readonly string[]).includes(x.name));
|
|
203
|
-
if (!t) {
|
|
204
|
-
// nothing to check with: the first scheme the server accepts
|
|
205
|
-
this.picked = { scheme, verified: false };
|
|
206
|
-
return c;
|
|
207
|
-
}
|
|
208
|
-
const r = await c.callTool(t.name, {});
|
|
209
|
-
if (!r.isError && arr(resultValue(r), "resources").length) {
|
|
210
|
-
this.picked = { scheme, verified: true };
|
|
211
|
-
return c;
|
|
212
|
-
}
|
|
213
|
-
fallback ??= { c, scheme };
|
|
214
|
-
} catch (e) {
|
|
215
|
-
err ??= e;
|
|
216
|
-
}
|
|
217
|
-
}
|
|
218
|
-
if (fallback) {
|
|
219
|
-
this.picked = { scheme: fallback.scheme, verified: false };
|
|
220
|
-
return fallback.c;
|
|
221
|
-
}
|
|
222
|
-
throw err;
|
|
223
|
-
}
|
|
224
|
-
|
|
225
|
-
/** The MCP auth scheme this client uses, after connecting; `verified` when it proved to reach a site. */
|
|
226
|
-
async authScheme(): Promise<{ scheme: JiraAuth; verified: boolean }> {
|
|
227
|
-
await this.mcp();
|
|
228
|
-
return this.picked!;
|
|
164
|
+
this.mcp = new McpClient(opts.mcpUrl ?? MCP_URL, { authorization: bearer(creds) }, this.fetchFn, opts.mcp);
|
|
229
165
|
}
|
|
230
166
|
|
|
231
167
|
get site() {
|
|
@@ -236,7 +172,7 @@ export class JiraClient {
|
|
|
236
172
|
}
|
|
237
173
|
|
|
238
174
|
private async tool(op: Op): Promise<McpTool | undefined> {
|
|
239
|
-
const tools = await
|
|
175
|
+
const tools = await this.mcp.listTools();
|
|
240
176
|
for (const n of TOOLS[op]) {
|
|
241
177
|
const t = tools.find((x) => x.name === n);
|
|
242
178
|
if (t) return t;
|
|
@@ -260,76 +196,55 @@ export class JiraClient {
|
|
|
260
196
|
private async call(op: Op, logical: Record<string, unknown>): Promise<JiraResult<unknown>> {
|
|
261
197
|
try {
|
|
262
198
|
const t = await this.tool(op);
|
|
263
|
-
if (!t) return { ok: false, error:
|
|
199
|
+
if (!t) return { ok: false, error: missingTool(op) };
|
|
264
200
|
const needsCloud = t.inputSchema?.properties && "cloudId" in t.inputSchema.properties;
|
|
265
201
|
const args = this.args(t, { ...(needsCloud ? { cloudId: await this.cloudId() } : {}), ...logical });
|
|
266
|
-
const r = await
|
|
267
|
-
if (r.isError) return { ok: false, error: `${t.name}: ${resultText(r).slice(0, 400)}` };
|
|
268
|
-
return { ok: true, value: resultValue(r)
|
|
202
|
+
const r = await this.mcp.callTool(t.name, args, { idempotent: READ_OPS.has(op) });
|
|
203
|
+
if (r.isError) return { ok: false, error: explain(`${t.name}: ${resultText(r).slice(0, 400)}`) };
|
|
204
|
+
return { ok: true, value: resultValue(r) };
|
|
269
205
|
} catch (e) {
|
|
270
|
-
return { ok: false, error: (e as Error).message };
|
|
206
|
+
return { ok: false, error: explain((e as Error).message) };
|
|
271
207
|
}
|
|
272
208
|
}
|
|
273
209
|
|
|
274
|
-
/** The site's cloudId: configured, else
|
|
275
|
-
*
|
|
210
|
+
/** The site's cloudId: configured, else the token's accessible resource for this site. A site the token
|
|
211
|
+
* cannot reach is an error here, not a guess passed on to every call. */
|
|
276
212
|
cloudId(): Promise<string> {
|
|
277
213
|
if (this.cloudIdFixed) return Promise.resolve(this.cloudIdFixed);
|
|
278
214
|
this.cloudIdP ??= (async () => {
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
}
|
|
298
|
-
return this.creds.site;
|
|
299
|
-
})();
|
|
215
|
+
const t = await this.tool("resources");
|
|
216
|
+
if (!t) throw new Error(missingTool("resources"));
|
|
217
|
+
const r = await this.mcp.callTool(t.name, {}, { idempotent: true });
|
|
218
|
+
if (r.isError) throw new Error(`${t.name}: ${resultText(r).slice(0, 300)}`);
|
|
219
|
+
const sites = arr(resultValue(r), "resources").map(rec);
|
|
220
|
+
const hit = sites.find((x) => str(x.url).replace(/^https?:\/\//, "").replace(/\/$/, "") === this.creds.site);
|
|
221
|
+
const id = str(hit?.cloudId ?? hit?.id);
|
|
222
|
+
if (!id)
|
|
223
|
+
throw new Error(
|
|
224
|
+
sites.length
|
|
225
|
+
? `the token reaches ${sites.map((x) => str(x.url).replace(/^https?:\/\//, "")).join(", ")}, not ${this.creds.site}`
|
|
226
|
+
: `the token reaches no Atlassian site — it must be a scoped API token (read:jira:agent-interface, write:jira:agent-interface) of an account on ${this.creds.site}`,
|
|
227
|
+
);
|
|
228
|
+
return id;
|
|
229
|
+
})().catch((e) => {
|
|
230
|
+
this.cloudIdP = undefined;
|
|
231
|
+
throw e;
|
|
232
|
+
});
|
|
300
233
|
return this.cloudIdP;
|
|
301
234
|
}
|
|
302
235
|
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
/** Jira REST with the same token (always Basic `email:token`, scoped or not) — only for what the MCP
|
|
308
|
-
* server cannot do. */
|
|
309
|
-
private async rest(method: string, p: string, body?: unknown, extra: Record<string, string> = {}): Promise<JiraResult<unknown>> {
|
|
236
|
+
/** Everything sync needs, checked once: the token reaches the site, names its user, and the server offers
|
|
237
|
+
* every tool dev-flow calls (a missing write tool means a missing write scope). */
|
|
238
|
+
async check(): Promise<JiraResult<JiraUser>> {
|
|
310
239
|
try {
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
headers["content-type"] = "application/json";
|
|
316
|
-
payload = JSON.stringify(body);
|
|
317
|
-
}
|
|
318
|
-
let res = await this.fetchFn(`${await this.restBase()}${p}`, { method, headers, body: payload });
|
|
319
|
-
if ((res.status === 401 || res.status === 403 || res.status === 404) && !this.gateway) {
|
|
320
|
-
// a scoped API token answers only through api.atlassian.com/ex/jira/<cloudId>
|
|
321
|
-
const id = await this.cloudId();
|
|
322
|
-
if (/^[0-9a-f-]{36}$/.test(id)) {
|
|
323
|
-
this.gateway = `https://api.atlassian.com/ex/jira/${id}/rest/api/3`;
|
|
324
|
-
res = await this.fetchFn(`${this.gateway}${p}`, { method, headers, body: payload });
|
|
325
|
-
}
|
|
326
|
-
}
|
|
327
|
-
const text = await res.text();
|
|
328
|
-
if (!res.ok) return { ok: false, error: `Jira REST ${method} ${p}: HTTP ${res.status} ${text.slice(0, 300)}` };
|
|
329
|
-
return { ok: true, value: text ? JSON.parse(text) : undefined, via: "rest" };
|
|
240
|
+
await this.cloudId();
|
|
241
|
+
const tools = await this.mcp.listTools();
|
|
242
|
+
const missing = (Object.keys(TOOLS) as Op[]).filter((op) => !TOOLS[op].some((n) => tools.some((x) => x.name === n)));
|
|
243
|
+
if (missing.length) return { ok: false, error: missing.map(missingTool).join("; ") };
|
|
330
244
|
} catch (e) {
|
|
331
|
-
return { ok: false, error: (e as Error).message };
|
|
245
|
+
return { ok: false, error: explain((e as Error).message) };
|
|
332
246
|
}
|
|
247
|
+
return this.me();
|
|
333
248
|
}
|
|
334
249
|
|
|
335
250
|
async me(): Promise<JiraResult<JiraUser>> {
|
|
@@ -353,8 +268,7 @@ export class JiraClient {
|
|
|
353
268
|
return { ok: true, value: arr(r.value).map(rec).map((t) => ({ id: str(t.id), name: str(t.name), subtask: t.subtask === true || t.hierarchyLevel === -1 })).filter((t) => t.name) };
|
|
354
269
|
}
|
|
355
270
|
|
|
356
|
-
/** The statuses of each issue type's workflow in a project
|
|
357
|
-
* type, else REST `/project/{key}/statuses` (the one call grouped by issue type). */
|
|
271
|
+
/** The statuses of each issue type's workflow in a project (`listJiraStatuses`, mode "project"). */
|
|
358
272
|
async statuses(project: string): Promise<JiraResult<Record<string, StatusInfo[]>>> {
|
|
359
273
|
const toInfo = (s: Record<string, unknown>): StatusInfo => ({ name: str(s.name), category: str(rec(s.statusCategory).key ?? s.statusCategory ?? s.category) || undefined });
|
|
360
274
|
const grouped = (v: unknown) => {
|
|
@@ -371,10 +285,9 @@ export class JiraClient {
|
|
|
371
285
|
return Object.fromEntries(list.map((t) => [str(t.name), (t.statuses as unknown[]).map(rec).map(toInfo)]));
|
|
372
286
|
};
|
|
373
287
|
const m = await this.call("statuses", { mode: "project", project });
|
|
374
|
-
if (m.ok
|
|
375
|
-
const
|
|
376
|
-
|
|
377
|
-
return { ok: false, error: !m.ok ? m.error : !r.ok ? r.error : "no per-issue-type statuses in the answer" };
|
|
288
|
+
if (!m.ok) return m;
|
|
289
|
+
const g = grouped(m.value);
|
|
290
|
+
return g ? { ok: true, value: g } : { ok: false, error: `listJiraStatuses: no per-issue-type statuses in ${JSON.stringify(m.value).slice(0, 200)}` };
|
|
378
291
|
}
|
|
379
292
|
|
|
380
293
|
async issue(key: string): Promise<JiraResult<JiraIssue>> {
|
|
@@ -398,17 +311,25 @@ export class JiraClient {
|
|
|
398
311
|
};
|
|
399
312
|
}
|
|
400
313
|
|
|
314
|
+
/** The newest comments, newest first: pages of 20 (the server's cap) up to COMMENTS_MAX. */
|
|
401
315
|
async comments(key: string): Promise<JiraResult<JiraComment[]>> {
|
|
402
316
|
const toC = (c: Record<string, unknown>): JiraComment => {
|
|
403
317
|
const a = rec(c.author);
|
|
404
318
|
return { id: str(c.id), authorId: str(a.accountId), authorName: str(a.displayName), body: adfText(c.body ?? c.renderedBody).trim(), created: str(c.created), updated: str(c.updated) || undefined };
|
|
405
319
|
};
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
320
|
+
const out: JiraComment[] = [];
|
|
321
|
+
for (let startAt = 0; out.length < COMMENTS_MAX; ) {
|
|
322
|
+
// "full": the default compact view leaves out the author's accountId, which decides who answered
|
|
323
|
+
const m = await this.call("comments", { issue: key, max: COMMENTS_PAGE, order: "-created", view: "full", ...(startAt ? { startAt } : {}) });
|
|
324
|
+
if (!m.ok) return out.length ? { ok: true, value: out } : m;
|
|
325
|
+
const page = arr(m.value).map(rec);
|
|
326
|
+
out.push(...page.map(toC).filter((c) => c.id));
|
|
327
|
+
const v = rec(m.value);
|
|
328
|
+
const total = typeof v.total === "number" ? v.total : undefined;
|
|
329
|
+
startAt += page.length;
|
|
330
|
+
if (!page.length || v.isLast === true || (total !== undefined && startAt >= total) || (v.isLast === undefined && total === undefined && page.length < COMMENTS_PAGE)) break;
|
|
331
|
+
}
|
|
332
|
+
return { ok: true, value: out.slice(0, COMMENTS_MAX) };
|
|
412
333
|
}
|
|
413
334
|
|
|
414
335
|
/** Post a comment (markdown); returns its id. */
|
|
@@ -416,79 +337,43 @@ export class JiraClient {
|
|
|
416
337
|
const t = await this.tool("comment").catch(() => undefined);
|
|
417
338
|
const takesFormat = !!t && Object.keys(t.inputSchema?.properties ?? {}).some((p) => ARGS.format.includes(p));
|
|
418
339
|
const m = await this.call("comment", { issue: key, body: markdown, ...(takesFormat ? { format: "markdown" } : {}) });
|
|
419
|
-
if (m.ok)
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
}
|
|
423
|
-
const r = await this.rest("POST", `/issue/${encodeURIComponent(key)}/comment`, { body: toAdf(markdown) });
|
|
424
|
-
if (r.ok) return { ok: true, value: str(rec(r.value).id), via: "rest" };
|
|
425
|
-
return m;
|
|
340
|
+
if (!m.ok) return m;
|
|
341
|
+
const v = rec(m.value);
|
|
342
|
+
return { ok: true, value: str(v.commentId ?? v.id ?? rec(v.comment).id) };
|
|
426
343
|
}
|
|
427
344
|
|
|
428
|
-
/** v2's two-phase upload: phase 1 (filePath) mints a short-lived Atlassian Media
|
|
429
|
-
* read but never run; we send the bytes ourselves; phase 2 (fileId) attaches the
|
|
430
|
-
|
|
431
|
-
const p1 = await this.call("upload", { issue: key, filePath: path.resolve(file) });
|
|
432
|
-
if (!p1.ok) return p1;
|
|
433
|
-
const v = rec(p1.value);
|
|
434
|
-
const req = parseUploadCommand(str(v.uploadCommand));
|
|
435
|
-
if (!req) return { ok: false, error: "the upload step returned no Atlassian Media request dev-flow can send" };
|
|
436
|
-
try {
|
|
437
|
-
const res = await this.fetchFn(req.url, { method: "POST", headers: { ...req.headers, "content-type": mimeOf(file) }, body: data as unknown as string });
|
|
438
|
-
const text = await res.text();
|
|
439
|
-
if (!res.ok) return { ok: false, error: `Atlassian Media upload: HTTP ${res.status} ${text.slice(0, 200)}` };
|
|
440
|
-
const j = rec(JSON.parse(text)); // rec() already unwraps { data: … }
|
|
441
|
-
const fileId = str(j.id ?? rec(j.data).id);
|
|
442
|
-
if (!fileId) return { ok: false, error: `Atlassian Media upload: no file id in ${text.slice(0, 200)}` };
|
|
443
|
-
const p2 = await this.call("upload", { issue: key, fileId });
|
|
444
|
-
return p2.ok ? { ok: true, value: path.basename(file), via: "mcp" } : p2;
|
|
445
|
-
} catch (e) {
|
|
446
|
-
return { ok: false, error: `Atlassian Media upload: ${(e as Error).message}` };
|
|
447
|
-
}
|
|
448
|
-
}
|
|
449
|
-
|
|
450
|
-
/** Attach a local file: MCP (content, or the two-phase media upload), else REST multipart. */
|
|
345
|
+
/** Attach a local file with v2's two-phase upload: phase 1 (filePath) mints a short-lived Atlassian Media
|
|
346
|
+
* upload — a curl command we read but never run; we send the bytes ourselves; phase 2 (fileId) attaches the
|
|
347
|
+
* file to the issue. */
|
|
451
348
|
async upload(key: string, file: string): Promise<JiraResult<string>> {
|
|
452
|
-
const data = readFileSync(file);
|
|
453
349
|
const name = path.basename(file);
|
|
454
|
-
const
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
mcpError = r.error;
|
|
461
|
-
}
|
|
462
|
-
if (t && props.some((p) => ARGS.file.includes(p))) {
|
|
463
|
-
const m = await this.call("upload", { issue: key, file: data.toString("base64"), filename: name, mime: mimeOf(file) });
|
|
464
|
-
if (m.ok) return { ok: true, value: name, via: "mcp" };
|
|
350
|
+
const fail = (why: string): JiraResult<string> => ({ ok: false, error: `attach ${name}: ${why}` });
|
|
351
|
+
let data: Buffer;
|
|
352
|
+
try {
|
|
353
|
+
data = readFileSync(file);
|
|
354
|
+
} catch (e) {
|
|
355
|
+
return fail((e as Error).message);
|
|
465
356
|
}
|
|
466
|
-
const
|
|
467
|
-
|
|
468
|
-
const
|
|
357
|
+
const p1 = await this.call("upload", { issue: key, filePath: path.resolve(file) });
|
|
358
|
+
if (!p1.ok) return fail(p1.error);
|
|
359
|
+
const req = parseUploadCommand(str(rec(p1.value).uploadCommand));
|
|
360
|
+
if (!req) return fail("the upload step returned no Atlassian Media request dev-flow can send");
|
|
469
361
|
try {
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
body: body as unknown as string,
|
|
476
|
-
});
|
|
477
|
-
let res = await send(await this.restBase());
|
|
478
|
-
if ((res.status === 401 || res.status === 403 || res.status === 404) && !this.gateway) {
|
|
479
|
-
const id = await this.cloudId();
|
|
480
|
-
if (/^[0-9a-f-]{36}$/.test(id)) {
|
|
481
|
-
this.gateway = `https://api.atlassian.com/ex/jira/${id}/rest/api/3`;
|
|
482
|
-
res = await send(this.gateway);
|
|
483
|
-
}
|
|
484
|
-
}
|
|
485
|
-
if (!res.ok) {
|
|
486
|
-
const why = res.status === 401 || res.status === 403 || res.status === 404 ? "Jira's REST API did not accept the token either" : (await res.text()).slice(0, 200);
|
|
487
|
-
return { ok: false, error: `attach ${name}: ${mcpError ? `${mcpError}; REST fallback: ` : ""}HTTP ${res.status} — ${why}` };
|
|
362
|
+
let res: Awaited<ReturnType<FetchLike>> | undefined;
|
|
363
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
364
|
+
// the upload only stores bytes under a fresh id: sending it again cannot attach twice
|
|
365
|
+
res = await this.fetchFn(req.url, { method: "POST", headers: { ...req.headers, "content-type": mimeOf(file) }, body: data as unknown as string });
|
|
366
|
+
if (res.ok || !(res.status === 429 || res.status >= 500)) break;
|
|
488
367
|
}
|
|
489
|
-
|
|
368
|
+
const text = await res!.text();
|
|
369
|
+
if (!res!.ok) return fail(`Atlassian Media upload: HTTP ${res!.status} ${text.slice(0, 200)}`);
|
|
370
|
+
const j = rec(JSON.parse(text)); // rec() already unwraps { data: … }
|
|
371
|
+
const fileId = str(j.id ?? rec(j.data).id);
|
|
372
|
+
if (!fileId) return fail(`Atlassian Media upload: no file id in ${text.slice(0, 200)}`);
|
|
373
|
+
const p2 = await this.call("upload", { issue: key, fileId });
|
|
374
|
+
return p2.ok ? { ok: true, value: name } : fail(p2.error);
|
|
490
375
|
} catch (e) {
|
|
491
|
-
return
|
|
376
|
+
return fail(`Atlassian Media upload: ${(e as Error).message}`);
|
|
492
377
|
}
|
|
493
378
|
}
|
|
494
379
|
|
|
@@ -501,11 +386,9 @@ export class JiraClient {
|
|
|
501
386
|
const typeVal = types?.ok ? (types.value.find((x) => x.name.toLowerCase() === type.toLowerCase())?.id ?? type) : type;
|
|
502
387
|
const takesFormat = props.some((p) => ARGS.format.includes(p));
|
|
503
388
|
const m = await this.call("create", { project, issueType: typeVal, summary, description: description || undefined, ...(takesFormat && description ? { format: "markdown" } : {}) });
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
if (r.ok && keyOf(r.value)) return { ok: true, value: keyOf(r.value), via: "rest" };
|
|
508
|
-
return m.ok ? { ok: false, error: `created, but no key in the answer: ${JSON.stringify(m.value).slice(0, 200)}` } : m;
|
|
389
|
+
if (!m.ok) return m;
|
|
390
|
+
const k = str(rec(m.value).key ?? rec(rec(m.value).issue).key);
|
|
391
|
+
return k ? { ok: true, value: k } : { ok: false, error: `created, but no key in the answer: ${JSON.stringify(m.value).slice(0, 200)}` };
|
|
509
392
|
}
|
|
510
393
|
|
|
511
394
|
async transitions(key: string): Promise<JiraResult<{ id: string; name: string; to: string }[]>> {
|
package/src/jira/creds.ts
CHANGED
|
@@ -1,26 +1,20 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Jira credentials — a
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
* Never printed, never written to project.md or to a
|
|
2
|
+
* Jira credentials — a scoped Atlassian Cloud API token (`read:jira:agent-interface`,
|
|
3
|
+
* `write:jira:agent-interface`) for the Atlassian Rovo MCP server, sent as `Authorization: Bearer <token>`.
|
|
4
|
+
* That is dev-flow's only path to Jira: no REST, no Basic auth, so no email.
|
|
5
|
+
*
|
|
6
|
+
* They live outside the repo: `~/.pi/agent/dev-flow/jira.json` (mode 0600), written by `/flow jira login`;
|
|
7
|
+
* `JIRA_API_TOKEN` (with `JIRA_SITE`) overrides the file. Never printed, never written to project.md or to a
|
|
8
|
+
* comment. Older files carry `email` / `auth` next to the token: they still load, and those fields are ignored.
|
|
8
9
|
*/
|
|
9
10
|
import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
10
11
|
import os from "node:os";
|
|
11
12
|
import path from "node:path";
|
|
12
13
|
|
|
13
|
-
/** How the token goes to the MCP server: `Bearer <token>` or Basic `email:token`. */
|
|
14
|
-
export type JiraAuth = "bearer" | "basic";
|
|
15
|
-
export const isJiraAuth = (v: unknown): v is JiraAuth => v === "bearer" || v === "basic";
|
|
16
|
-
|
|
17
14
|
export interface JiraCreds {
|
|
18
15
|
site: string; // acme.atlassian.net
|
|
19
|
-
email: string;
|
|
20
16
|
token: string;
|
|
21
17
|
source: "env" | "file";
|
|
22
|
-
/** the MCP auth scheme known to work; unset → probed (Bearer first) */
|
|
23
|
-
auth?: JiraAuth;
|
|
24
18
|
}
|
|
25
19
|
|
|
26
20
|
export const credsPath = (home = os.homedir()) => path.join(process.env.PI_CODING_AGENT_DIR ?? path.join(home, ".pi", "agent"), "dev-flow", "jira.json");
|
|
@@ -33,7 +27,7 @@ export const normSite = (s: string) =>
|
|
|
33
27
|
.replace(/\/.*$/, "")
|
|
34
28
|
.toLowerCase();
|
|
35
29
|
|
|
36
|
-
type Store = { sites?: Record<string, {
|
|
30
|
+
type Store = { sites?: Record<string, { token: string; [legacy: string]: unknown }> };
|
|
37
31
|
|
|
38
32
|
function readStore(file: string): Store {
|
|
39
33
|
try {
|
|
@@ -46,34 +40,20 @@ function readStore(file: string): Store {
|
|
|
46
40
|
/** Credentials for `site` (or for the only/first stored site when none is named), or null. */
|
|
47
41
|
export function loadCreds(site?: string, env: NodeJS.ProcessEnv = process.env, file = credsPath()): JiraCreds | null {
|
|
48
42
|
const want = site ? normSite(site) : env.JIRA_SITE ? normSite(env.JIRA_SITE) : undefined;
|
|
49
|
-
if (env.
|
|
50
|
-
return { site: want ?? normSite(env.JIRA_SITE!), email: env.JIRA_EMAIL, token: env.JIRA_API_TOKEN, source: "env", ...(isJiraAuth(env.JIRA_AUTH) ? { auth: env.JIRA_AUTH } : {}) };
|
|
43
|
+
if (env.JIRA_API_TOKEN && (want || env.JIRA_SITE)) return { site: want ?? normSite(env.JIRA_SITE!), token: env.JIRA_API_TOKEN.trim(), source: "env" };
|
|
51
44
|
const sites = readStore(file).sites ?? {};
|
|
52
45
|
const key = want ?? Object.keys(sites)[0];
|
|
53
46
|
const hit = key ? sites[key] : undefined;
|
|
54
|
-
return hit && key ? { site: key,
|
|
47
|
+
return hit?.token && key ? { site: key, token: hit.token, source: "file" } : null;
|
|
55
48
|
}
|
|
56
49
|
|
|
57
|
-
export function saveCreds(site: string,
|
|
50
|
+
export function saveCreds(site: string, token: string, file = credsPath()): void {
|
|
58
51
|
mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
59
52
|
const store = existsSync(file) ? readStore(file) : {};
|
|
60
|
-
store.sites = { ...(store.sites ?? {}), [normSite(site)]: {
|
|
61
|
-
writeFileSync(file, `${JSON.stringify(store, null, "\t")}\n`, { mode: 0o600 });
|
|
62
|
-
chmodSync(file, 0o600);
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
/** Remember the MCP auth scheme that worked for a stored login (no-op when the site or token changed). */
|
|
66
|
-
export function saveAuth(creds: Pick<JiraCreds, "site" | "token">, auth: JiraAuth, file = credsPath()): void {
|
|
67
|
-
if (!existsSync(file)) return;
|
|
68
|
-
const store = readStore(file);
|
|
69
|
-
const hit = store.sites?.[creds.site];
|
|
70
|
-
if (!hit || hit.token !== creds.token || hit.auth === auth) return;
|
|
71
|
-
hit.auth = auth;
|
|
53
|
+
store.sites = { ...(store.sites ?? {}), [normSite(site)]: { token: token.trim() } };
|
|
72
54
|
writeFileSync(file, `${JSON.stringify(store, null, "\t")}\n`, { mode: 0o600 });
|
|
73
55
|
chmodSync(file, 0o600);
|
|
74
56
|
}
|
|
75
57
|
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
/** The MCP server's Authorization header for `scheme` (default: the stored one, else Bearer). */
|
|
79
|
-
export const mcpAuth = (c: Pick<JiraCreds, "email" | "token" | "auth">, scheme: JiraAuth = c.auth ?? "bearer") => (scheme === "bearer" ? `Bearer ${c.token}` : basicAuth(c));
|
|
58
|
+
/** The MCP server's Authorization header. */
|
|
59
|
+
export const bearer = (c: Pick<JiraCreds, "token">) => `Bearer ${c.token}`;
|