pi-mono-all 1.2.3 → 1.2.5

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 CHANGED
@@ -1,5 +1,17 @@
1
1
  # pi-mono-all
2
2
 
3
+ ## 1.2.5
4
+
5
+ ### Patch Changes
6
+
7
+ - Bundle `pi-mono-linear@0.2.4` with automatic Markdown description image reading for `linear_get_issue` on vision-capable models.
8
+
9
+ ## 1.2.4
10
+
11
+ ### Patch Changes
12
+
13
+ - Bundle `pi-mono-sentinel@1.12.0` with project-scoped config stored under the Pi agent directory instead of the current working directory.
14
+
3
15
  ## 1.2.3
4
16
 
5
17
  ### Patch Changes
@@ -1,5 +1,11 @@
1
1
  # pi-mono-linear
2
2
 
3
+ ## 0.2.4
4
+
5
+ ### Patch Changes
6
+
7
+ - Added automatic Markdown description image reading to `linear_get_issue` for vision-capable models. Private `uploads.linear.app` images are streamed in memory with Linear auth and attached as native image blocks; text-only models skip downloads with a clear note.
8
+
3
9
  ## 0.2.3
4
10
 
5
11
  ### Patch Changes
@@ -132,11 +132,28 @@ Linear API keys are sent in the `Authorization` header as the raw key value; do
132
132
  - `linear_create_issue` accepts either a team UUID or a team key; keys are resolved to UUIDs before the Linear mutation.
133
133
  - Use `linear_search_issues` for keyword lookup.
134
134
  - Use `linear_get_issue` before updating an issue or creating a comment.
135
+ - `linear_get_issue` automatically parses Markdown images embedded in the issue description. When the active model supports image input, private `uploads.linear.app` images are downloaded in memory with Linear auth and attached to the tool result; images are not written to disk.
136
+ - If the active model does not support image input, `linear_get_issue` does not download images and returns a clear skipped-images note plus image metadata.
135
137
  - Use `linear_list_issues` for filtered issue lists by team, assignee, status, and limit.
136
138
  - Use `linear_upload_file` to upload a local image, video, or generic file and return a Linear asset URL.
137
139
  - Use `linear_upload_file_to_issue_comment` after `linear_get_issue` to upload a local file and post a Markdown comment. Images are rendered with image Markdown; other files use links.
138
140
  - File upload tool results return sanitized metadata and the stable Linear asset URL. They do not return local file bytes, signed upload URLs, or upload headers.
139
141
 
142
+ ## Issue description images
143
+
144
+ Linear issue screenshots embedded in descriptions are stored as Markdown image links, for example:
145
+
146
+ ```md
147
+ ![Screenshot](https://uploads.linear.app/...)
148
+ ```
149
+
150
+ These are part of the issue description Markdown, not GraphQL attachment objects. `linear_get_issue` reads them automatically when possible:
151
+
152
+ - Vision-capable model: images are streamed into memory, base64-encoded, and returned as native image blocks alongside the Markdown description.
153
+ - Text-only model: image downloads are skipped to avoid unnecessary network and payload work; the response includes a note explaining that a vision-capable model is required.
154
+ - No files are saved locally by default.
155
+ - The default safety limits are 10 description images and 10 MiB per image.
156
+
140
157
  ## Troubleshooting
141
158
 
142
159
  ### Missing auth key
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-mono-linear",
3
- "version": "0.2.3",
3
+ "version": "0.2.4",
4
4
  "description": "Pi extension and skill for Linear GraphQL tools",
5
5
  "type": "module",
6
6
  "keywords": [
@@ -27,6 +27,8 @@ If auth is missing, invalid, or expired, do **not** ask the user to paste the ke
27
27
  - Use `linear_workspace_metadata` first when team/project/state/label/user IDs are unknown.
28
28
  - Use `linear_search_issues` for keyword lookup.
29
29
  - Use `linear_get_issue` before updating or commenting.
30
+ - Use `linear_get_issue` to inspect Linear issues; Markdown images embedded in the issue description are automatically included when the active model supports image input.
31
+ - If `linear_get_issue` reports description images were skipped because the current model does not support images, ask the user to switch to a vision-capable model before interpreting screenshots.
30
32
  - Use `linear_list_issues` for filtered issue lists by team, assignee, status, or limit.
31
33
  - Use `linear_create_issue` to create issues once the team ID is known.
32
34
  - Use `linear_update_issue` to change title, description, priority, state, or assignee.
@@ -76,6 +78,14 @@ If auth is missing, invalid, or expired, do **not** ask the user to paste the ke
76
78
  - `linear_upload_file`
77
79
  - `linear_upload_file_to_issue_comment`
78
80
 
81
+ ## Issue Description Images
82
+
83
+ - Linear issue screenshots embedded in descriptions are Markdown images, not necessarily GraphQL attachment objects.
84
+ - `linear_get_issue` parses description Markdown image links like `![Screenshot](https://uploads.linear.app/...)`.
85
+ - When the active model supports image input, `linear_get_issue` downloads private Linear image URLs in memory with Linear auth and attaches native image blocks to the result.
86
+ - When the active model is text-only, image downloads are skipped and the tool returns a note plus image metadata.
87
+ - Description images are not written to disk by default.
88
+
79
89
  ## File Upload Notes
80
90
 
81
91
  - Upload tools accept local file paths only; they do not read folders recursively.
@@ -5,6 +5,7 @@ import { createHttpClient, type HttpClient } from "pi-common/http-client";
5
5
  import { createRateLimiter, type RateLimiter } from "pi-common/rate-limiter";
6
6
  import { readFile, stat } from "node:fs/promises";
7
7
  import { basename, extname, resolve } from "node:path";
8
+ import type { MarkdownImageReference } from "./linear-markdown-images.js";
8
9
  import * as queries from "./linear-queries.js";
9
10
 
10
11
  export interface LinearClientOptions {
@@ -46,6 +47,20 @@ export interface UploadFileInput {
46
47
  makePublic?: boolean;
47
48
  }
48
49
 
50
+ export interface DownloadIssueImageInput {
51
+ reference: MarkdownImageReference;
52
+ maxBytes?: number;
53
+ signal?: AbortSignal;
54
+ }
55
+
56
+ export interface DownloadedIssueImageResult {
57
+ reference: MarkdownImageReference;
58
+ filename: string;
59
+ mimeType: string;
60
+ size: number;
61
+ data: string;
62
+ }
63
+
49
64
  interface UploadFileHeader {
50
65
  key: string;
51
66
  value: string;
@@ -98,6 +113,8 @@ interface GraphQlResponse<T> {
98
113
 
99
114
  const cache = createTtlCache<unknown>({ defaultTtlMs: 60_000, maxEntries: 100 });
100
115
  const DEFAULT_MAX_UPLOAD_BYTES = 50 * 1024 * 1024;
116
+ const DEFAULT_MAX_DOWNLOAD_IMAGE_BYTES = 10 * 1024 * 1024;
117
+ const SUPPORTED_INLINE_IMAGE_TYPES = new Set(["image/png", "image/jpeg", "image/webp", "image/gif"]);
101
118
 
102
119
  export class LinearClient {
103
120
  private readonly http: HttpClient;
@@ -224,6 +241,10 @@ export class LinearClient {
224
241
  };
225
242
  }
226
243
 
244
+ async downloadIssueImage(input: DownloadIssueImageInput): Promise<DownloadedIssueImageResult> {
245
+ return downloadIssueImage(input);
246
+ }
247
+
227
248
  listCycles(teamId?: string): Promise<unknown> {
228
249
  return teamId
229
250
  ? this.cached(`teamCycles:${teamId}`, () => this.graphql(queries.LIST_TEAM_CYCLES, { id: teamId }))
@@ -344,6 +365,131 @@ async function safeUploadBody(response: Response): Promise<unknown> {
344
365
  }
345
366
  }
346
367
 
368
+ async function downloadIssueImage(input: DownloadIssueImageInput): Promise<DownloadedIssueImageResult> {
369
+ const url = validateLinearImageUrl(input.reference.url);
370
+ const maxBytes = input.maxBytes ?? DEFAULT_MAX_DOWNLOAD_IMAGE_BYTES;
371
+ if (!Number.isFinite(maxBytes) || maxBytes <= 0) {
372
+ throw new ApiError("maxImageBytes must be a positive number", 400, { maxBytes }, "Linear");
373
+ }
374
+
375
+ const token = await readLinearToken();
376
+ const response = await downloadLinearFile(url, token, input.signal);
377
+ if (!response.ok) {
378
+ throw new ApiError(response.statusText || `Image download failed with HTTP ${response.status}`, response.status, await safeUploadBody(response), "Linear");
379
+ }
380
+ if (!response.body) {
381
+ throw new ApiError("Image download response did not include a body", 502, { url }, "Linear");
382
+ }
383
+
384
+ const contentLength = response.headers.get("content-length");
385
+ if (contentLength && Number(contentLength) > maxBytes) {
386
+ throw new ApiError(`Image is too large (${contentLength} bytes). Limit is ${maxBytes} bytes.`, 400, { size: Number(contentLength), maxBytes }, "Linear");
387
+ }
388
+
389
+ const bytes = await readResponseBytes(response.body, maxBytes);
390
+ const mimeType = detectSupportedImageMimeType(bytes, response.headers.get("content-type"));
391
+ if (!mimeType) {
392
+ throw new ApiError("Downloaded file is not a supported inline image", 415, { contentType: response.headers.get("content-type"), supportedTypes: [...SUPPORTED_INLINE_IMAGE_TYPES] }, "Linear");
393
+ }
394
+
395
+ return {
396
+ reference: input.reference,
397
+ filename: filenameForImageUrl(url, mimeType, input.reference.index),
398
+ mimeType,
399
+ size: bytes.byteLength,
400
+ data: Buffer.from(bytes).toString("base64"),
401
+ };
402
+ }
403
+
404
+ async function downloadLinearFile(url: string, token: string, signal?: AbortSignal): Promise<Response> {
405
+ const normalizedToken = token.replace(/^Bearer\s+/i, "").trim();
406
+ const rawResponse = await fetch(url, { method: "GET", headers: { Authorization: normalizedToken }, signal });
407
+ if (rawResponse.status !== 401 && rawResponse.status !== 403) return rawResponse;
408
+
409
+ // Linear personal API keys use `Authorization: <API_KEY>`, while OAuth access
410
+ // tokens use `Authorization: Bearer <ACCESS_TOKEN>`. The extension normally
411
+ // stores personal API keys, but this fallback keeps file reads compatible with
412
+ // OAuth-style tokens without requiring a separate auth configuration.
413
+ await rawResponse.body?.cancel().catch(() => undefined);
414
+ return fetch(url, { method: "GET", headers: { Authorization: `Bearer ${normalizedToken}` }, signal });
415
+ }
416
+
417
+ function validateLinearImageUrl(value: string): string {
418
+ let url: URL;
419
+ try {
420
+ url = new URL(value);
421
+ } catch {
422
+ throw new ApiError("Invalid image URL in Linear issue description", 400, { url: value }, "Linear");
423
+ }
424
+ if (url.protocol !== "https:") {
425
+ throw new ApiError("Only HTTPS Linear image URLs are supported", 400, { url: value }, "Linear");
426
+ }
427
+ if (url.hostname !== "uploads.linear.app") {
428
+ throw new ApiError("Only uploads.linear.app issue description images are supported", 400, { url: value, hostname: url.hostname }, "Linear");
429
+ }
430
+ return url.toString();
431
+ }
432
+
433
+ async function readResponseBytes(body: ReadableStream<Uint8Array>, maxBytes: number): Promise<Uint8Array> {
434
+ const reader = body.getReader();
435
+ const chunks: Uint8Array[] = [];
436
+ let total = 0;
437
+ try {
438
+ while (true) {
439
+ const { done, value } = await reader.read();
440
+ if (done) break;
441
+ if (!value) continue;
442
+ total += value.byteLength;
443
+ if (total > maxBytes) {
444
+ throw new ApiError(`Image is too large. Limit is ${maxBytes} bytes.`, 400, { size: total, maxBytes }, "Linear");
445
+ }
446
+ chunks.push(value);
447
+ }
448
+ } finally {
449
+ reader.releaseLock();
450
+ }
451
+ return Buffer.concat(chunks, total);
452
+ }
453
+
454
+ function detectSupportedImageMimeType(bytes: Uint8Array, contentType: string | null): string | undefined {
455
+ const magic = detectImageMimeTypeFromMagicBytes(bytes);
456
+ if (magic && SUPPORTED_INLINE_IMAGE_TYPES.has(magic)) return magic;
457
+
458
+ const normalized = contentType?.split(";")[0]?.trim().toLowerCase();
459
+ if (normalized && SUPPORTED_INLINE_IMAGE_TYPES.has(normalized)) return normalized;
460
+ return undefined;
461
+ }
462
+
463
+ function detectImageMimeTypeFromMagicBytes(bytes: Uint8Array): string | undefined {
464
+ if (bytes.length >= 8 && bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47 && bytes[4] === 0x0d && bytes[5] === 0x0a && bytes[6] === 0x1a && bytes[7] === 0x0a) return "image/png";
465
+ if (bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return "image/jpeg";
466
+ if (bytes.length >= 6) {
467
+ const signature = Buffer.from(bytes.slice(0, 6)).toString("ascii");
468
+ if (signature === "GIF87a" || signature === "GIF89a") return "image/gif";
469
+ }
470
+ if (bytes.length >= 12) {
471
+ const riff = Buffer.from(bytes.slice(0, 4)).toString("ascii");
472
+ const webp = Buffer.from(bytes.slice(8, 12)).toString("ascii");
473
+ if (riff === "RIFF" && webp === "WEBP") return "image/webp";
474
+ }
475
+ return undefined;
476
+ }
477
+
478
+ function filenameForImageUrl(url: string, mimeType: string, index: number): string {
479
+ const pathname = new URL(url).pathname;
480
+ const leaf = basename(pathname);
481
+ const extension = extensionForMimeType(mimeType);
482
+ if (leaf && leaf.includes(".")) return leaf;
483
+ return `linear-description-image-${index}.${extension}`;
484
+ }
485
+
486
+ function extensionForMimeType(mimeType: string): string {
487
+ if (mimeType === "image/jpeg") return "jpg";
488
+ if (mimeType === "image/webp") return "webp";
489
+ if (mimeType === "image/gif") return "gif";
490
+ return "png";
491
+ }
492
+
347
493
  function inferContentType(filePath: string): string {
348
494
  const extension = extname(filePath).toLowerCase();
349
495
  return CONTENT_TYPES[extension] ?? "application/octet-stream";
@@ -0,0 +1,91 @@
1
+ export interface MarkdownImageReference {
2
+ index: number;
3
+ source: "description";
4
+ altText: string;
5
+ url: string;
6
+ rawMarkdown: string;
7
+ line: number;
8
+ start: number;
9
+ end: number;
10
+ contextSnippet: string;
11
+ }
12
+
13
+ export interface ExtractMarkdownImagesOptions {
14
+ source?: MarkdownImageReference["source"];
15
+ contextLines?: number;
16
+ }
17
+
18
+ const MARKDOWN_IMAGE_RE = /!\[([^\]]*)\]\(\s*(<[^>]+>|[^\s)]+)(?:\s+["'][^"']*["'])?\s*\)/g;
19
+
20
+ export function extractMarkdownImages(markdown: string, options: ExtractMarkdownImagesOptions = {}): MarkdownImageReference[] {
21
+ const source = options.source ?? "description";
22
+ const contextLines = options.contextLines ?? 2;
23
+ const lineStarts = getLineStarts(markdown);
24
+ const lines = markdown.split("\n");
25
+ const references: MarkdownImageReference[] = [];
26
+
27
+ for (const match of markdown.matchAll(MARKDOWN_IMAGE_RE)) {
28
+ const rawMarkdown = match[0];
29
+ const rawUrl = match[2] ?? "";
30
+ const url = unwrapMarkdownUrl(rawUrl);
31
+ if (!url) continue;
32
+
33
+ const start = match.index ?? 0;
34
+ const end = start + rawMarkdown.length;
35
+ const line = lineForOffset(lineStarts, start);
36
+ references.push({
37
+ index: references.length + 1,
38
+ source,
39
+ altText: unescapeMarkdownText(match[1] ?? ""),
40
+ url,
41
+ rawMarkdown,
42
+ line,
43
+ start,
44
+ end,
45
+ contextSnippet: buildContextSnippet(lines, line, contextLines),
46
+ });
47
+ }
48
+
49
+ return references;
50
+ }
51
+
52
+ function unwrapMarkdownUrl(rawUrl: string): string {
53
+ const trimmed = rawUrl.trim();
54
+ if (trimmed.startsWith("<") && trimmed.endsWith(">")) return trimmed.slice(1, -1).trim();
55
+ return trimmed;
56
+ }
57
+
58
+ function unescapeMarkdownText(value: string): string {
59
+ return value.replace(/\\([\\\[\]])/g, "$1");
60
+ }
61
+
62
+ function getLineStarts(text: string): number[] {
63
+ const starts = [0];
64
+ for (let index = 0; index < text.length; index++) {
65
+ if (text[index] === "\n") starts.push(index + 1);
66
+ }
67
+ return starts;
68
+ }
69
+
70
+ function lineForOffset(lineStarts: number[], offset: number): number {
71
+ let low = 0;
72
+ let high = lineStarts.length - 1;
73
+ while (low <= high) {
74
+ const mid = Math.floor((low + high) / 2);
75
+ const start = lineStarts[mid] ?? 0;
76
+ const next = lineStarts[mid + 1] ?? Number.POSITIVE_INFINITY;
77
+ if (offset >= start && offset < next) return mid + 1;
78
+ if (offset < start) high = mid - 1;
79
+ else low = mid + 1;
80
+ }
81
+ return lineStarts.length;
82
+ }
83
+
84
+ function buildContextSnippet(lines: string[], line: number, contextLines: number): string {
85
+ const start = Math.max(1, line - contextLines);
86
+ const end = Math.min(lines.length, line + contextLines);
87
+ return lines
88
+ .slice(start - 1, end)
89
+ .map((text, index) => `${start + index}: ${text}`)
90
+ .join("\n");
91
+ }
@@ -15,7 +15,13 @@ export const OptionalTeamParams = Type.Object({ teamId: Type.Optional(TeamIdSche
15
15
  export const IdParams = Type.Object({ id: Type.String({ description: "Linear object ID" }), maxResponseChars: MaxResponseCharsSchema });
16
16
 
17
17
  export const LinearGetTeamParams = Type.Object({ teamId: TeamIdSchema, maxResponseChars: MaxResponseCharsSchema });
18
- export const LinearGetIssueParams = Type.Object({ issueId: IssueIdSchema, maxResponseChars: MaxResponseCharsSchema });
18
+ export const LinearGetIssueParams = Type.Object({
19
+ issueId: IssueIdSchema,
20
+ readDescriptionImages: Type.Optional(Type.Boolean({ description: "Read Markdown images embedded in the issue description when the active model supports image input. Defaults to true." })),
21
+ maxDescriptionImages: Type.Optional(Type.Number({ description: "Maximum number of description images to read. Defaults to 10.", minimum: 1, maximum: 50 })),
22
+ maxImageBytes: Type.Optional(Type.Number({ description: "Maximum bytes per description image before download is stopped. Defaults to 10 MiB.", minimum: 1 })),
23
+ maxResponseChars: MaxResponseCharsSchema,
24
+ });
19
25
  export const LinearGetProjectParams = Type.Object({ projectId: ProjectIdSchema, maxResponseChars: MaxResponseCharsSchema });
20
26
  export const LinearGetUserParams = Type.Object({ userId: UserIdSchema, maxResponseChars: MaxResponseCharsSchema });
21
27
  export const LinearGetDocumentParams = Type.Object({ documentId: Type.String({ description: "Linear document UUID" }), maxResponseChars: MaxResponseCharsSchema });
@@ -1,7 +1,8 @@
1
1
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import { registerAuthConfigurator, runWithAuthRetry, type AuthConfiguratorOptions } from "pi-common/auth-config";
3
3
  import { jsonToolResult } from "pi-common/tool-result";
4
- import { LinearClient, type UploadedFileResult } from "./linear-client.js";
4
+ import { LinearClient, type DownloadedIssueImageResult, type UploadedFileResult } from "./linear-client.js";
5
+ import { extractMarkdownImages, type MarkdownImageReference } from "./linear-markdown-images.js";
5
6
  import {
6
7
  EmptyParams,
7
8
  LinearCommentsParams,
@@ -23,6 +24,30 @@ import {
23
24
  OptionalTeamParams,
24
25
  } from "./linear-schemas.js";
25
26
 
27
+ type LinearToolContent = { type: "text"; text: string } | { type: "image"; data: string; mimeType: string };
28
+
29
+ interface DescriptionImageManifestEntry {
30
+ index: number;
31
+ source: "description";
32
+ altText: string;
33
+ url: string;
34
+ line: number;
35
+ contextSnippet: string;
36
+ status: "downloaded" | "skipped";
37
+ mimeType?: string;
38
+ size?: number;
39
+ filename?: string;
40
+ reason?: string;
41
+ }
42
+
43
+ interface LinearIssueNodeLike {
44
+ id?: string;
45
+ identifier?: string;
46
+ title?: string;
47
+ url?: string;
48
+ description?: string | null;
49
+ }
50
+
26
51
  const LINEAR_AUTH: AuthConfiguratorOptions = {
27
52
  service: "linear",
28
53
  displayName: "Linear",
@@ -57,6 +82,139 @@ function escapeMarkdownAltText(value: string): string {
57
82
  return value.replaceAll("[", "\\[").replaceAll("]", "\\]");
58
83
  }
59
84
 
85
+ function getIssueNode(result: unknown): LinearIssueNodeLike | undefined {
86
+ if (!result || typeof result !== "object") return undefined;
87
+ const issue = (result as { issue?: unknown }).issue;
88
+ if (!issue || typeof issue !== "object") return undefined;
89
+ return issue as LinearIssueNodeLike;
90
+ }
91
+
92
+ function modelSupportsImages(ctx: ExtensionContext): boolean {
93
+ return ctx.model?.input?.includes("image") ?? false;
94
+ }
95
+
96
+ function buildSkippedManifestEntry(reference: MarkdownImageReference, reason: string): DescriptionImageManifestEntry {
97
+ return {
98
+ index: reference.index,
99
+ source: reference.source,
100
+ altText: reference.altText,
101
+ url: reference.url,
102
+ line: reference.line,
103
+ contextSnippet: reference.contextSnippet,
104
+ status: "skipped",
105
+ reason,
106
+ };
107
+ }
108
+
109
+ function buildDownloadedManifestEntry(image: DownloadedIssueImageResult): DescriptionImageManifestEntry {
110
+ return {
111
+ index: image.reference.index,
112
+ source: image.reference.source,
113
+ altText: image.reference.altText,
114
+ url: image.reference.url,
115
+ line: image.reference.line,
116
+ contextSnippet: image.reference.contextSnippet,
117
+ status: "downloaded",
118
+ mimeType: image.mimeType,
119
+ size: image.size,
120
+ filename: image.filename,
121
+ };
122
+ }
123
+
124
+ function errorMessage(error: unknown): string {
125
+ return error instanceof Error ? error.message : String(error);
126
+ }
127
+
128
+ function appendImageReadingMetadata(result: unknown, imageReading: unknown): unknown {
129
+ if (!result || typeof result !== "object" || Array.isArray(result)) return { result, imageReading };
130
+ return { ...(result as Record<string, unknown>), imageReading };
131
+ }
132
+
133
+ function issueLabel(issue: LinearIssueNodeLike | undefined): string {
134
+ if (!issue) return "Linear issue";
135
+ return [issue.identifier, issue.title].filter(Boolean).join(" — ") || issue.id || "Linear issue";
136
+ }
137
+
138
+ function imageNote(reference: MarkdownImageReference, image: DownloadedIssueImageResult): string {
139
+ return [
140
+ `[Description image ${reference.index}: alt=${JSON.stringify(reference.altText || "image")}, line=${reference.line}, mimeType=${image.mimeType}, size=${image.size} bytes]`,
141
+ "Markdown context:",
142
+ reference.contextSnippet,
143
+ ].join("\n");
144
+ }
145
+
146
+ async function buildIssueResultWithDescriptionImages(options: {
147
+ client: LinearClient;
148
+ result: unknown;
149
+ ctx: ExtensionContext;
150
+ readDescriptionImages?: boolean;
151
+ maxDescriptionImages?: number;
152
+ maxImageBytes?: number;
153
+ maxResponseChars?: number;
154
+ signal?: AbortSignal;
155
+ }): Promise<{ content: LinearToolContent[]; details: Record<string, unknown> }> {
156
+ const issue = getIssueNode(options.result);
157
+ const description = issue?.description ?? "";
158
+ const references = typeof description === "string" ? extractMarkdownImages(description, { source: "description" }) : [];
159
+ const shouldReadImages = options.readDescriptionImages ?? true;
160
+ if (!references.length || !shouldReadImages) {
161
+ return jsonToolResult(options.result, { maxChars: options.maxResponseChars });
162
+ }
163
+
164
+ const maxImages = options.maxDescriptionImages ?? 10;
165
+ const selected = references.slice(0, maxImages);
166
+ const overflow = references.slice(maxImages);
167
+ const supportsImages = modelSupportsImages(options.ctx);
168
+ const manifest: DescriptionImageManifestEntry[] = [];
169
+ const imageContents: LinearToolContent[] = [];
170
+
171
+ if (!supportsImages) {
172
+ manifest.push(...references.map((reference) => buildSkippedManifestEntry(reference, "model_does_not_support_images")));
173
+ const note = `Description images detected but not downloaded because the current model does not support image input. Switch to a vision-capable model to inspect them.`;
174
+ const data = appendImageReadingMetadata(options.result, {
175
+ modelSupportsImages: false,
176
+ descriptionImagesFound: references.length,
177
+ descriptionImages: manifest,
178
+ note,
179
+ });
180
+ const base = jsonToolResult(data, { maxChars: options.maxResponseChars });
181
+ return {
182
+ content: [...base.content, { type: "text", text: `\n[${note}]` }],
183
+ details: { ...base.details, imageReading: { issue: issue ? { id: issue.id, identifier: issue.identifier, title: issue.title, url: issue.url } : undefined, descriptionImages: manifest } },
184
+ };
185
+ }
186
+
187
+ for (const reference of selected) {
188
+ try {
189
+ const image = await options.client.downloadIssueImage({ reference, maxBytes: options.maxImageBytes, signal: options.signal });
190
+ manifest.push(buildDownloadedManifestEntry(image));
191
+ imageContents.push({ type: "text", text: imageNote(reference, image) }, { type: "image", mimeType: image.mimeType, data: image.data });
192
+ } catch (error) {
193
+ manifest.push(buildSkippedManifestEntry(reference, errorMessage(error)));
194
+ imageContents.push({ type: "text", text: `[Description image ${reference.index} skipped: ${errorMessage(error)}]` });
195
+ }
196
+ }
197
+ for (const reference of overflow) {
198
+ manifest.push(buildSkippedManifestEntry(reference, `maxDescriptionImages limit (${maxImages}) reached`));
199
+ }
200
+
201
+ const data = appendImageReadingMetadata(options.result, {
202
+ modelSupportsImages: true,
203
+ descriptionImagesFound: references.length,
204
+ descriptionImagesRead: manifest.filter((entry) => entry.status === "downloaded").length,
205
+ descriptionImages: manifest,
206
+ });
207
+ const base = jsonToolResult(data, { maxChars: options.maxResponseChars });
208
+ const preamble: LinearToolContent = {
209
+ type: "text",
210
+ text: `\nRead ${manifest.filter((entry) => entry.status === "downloaded").length} of ${references.length} Markdown description image(s) for ${issueLabel(issue)}. Images are attached below in description order.`,
211
+ };
212
+ return {
213
+ content: [...base.content, preamble, ...imageContents],
214
+ details: { ...base.details, imageReading: { issue: issue ? { id: issue.id, identifier: issue.identifier, title: issue.title, url: issue.url } : undefined, descriptionImages: manifest } },
215
+ };
216
+ }
217
+
60
218
  export function registerLinearTools(pi: ExtensionAPI): void {
61
219
  const client = new LinearClient();
62
220
  registerAuthConfigurator(pi, LINEAR_AUTH);
@@ -127,10 +285,24 @@ export function registerLinearTools(pi: ExtensionAPI): void {
127
285
  pi.registerTool({
128
286
  name: "linear_get_issue",
129
287
  label: "Linear Get Issue",
130
- description: "Get full Linear issue details by UUID or identifier like ENG-123.",
288
+ description: "Get full Linear issue details by UUID or identifier like ENG-123. Markdown images embedded in the issue description are read and attached when the active model supports image input.",
289
+ promptGuidelines: [
290
+ "Use linear_get_issue to inspect Linear issues; if the issue description contains Markdown images and the active model supports image input, the images are downloaded in memory and attached to the tool result.",
291
+ "When linear_get_issue reports description images were skipped because the model does not support images, ask the user to switch to a vision-capable model before interpreting screenshots.",
292
+ ],
131
293
  parameters: LinearGetIssueParams,
132
- async execute(_id, params, _signal, _onUpdate, ctx) {
133
- return jsonToolResult(await withLinearAuth(ctx, () => client.getIssue(params.issueId)), { maxChars: params.maxResponseChars });
294
+ async execute(_id, params, signal, _onUpdate, ctx) {
295
+ const result = await withLinearAuth(ctx, () => client.getIssue(params.issueId));
296
+ return buildIssueResultWithDescriptionImages({
297
+ client,
298
+ result,
299
+ ctx,
300
+ readDescriptionImages: params.readDescriptionImages,
301
+ maxDescriptionImages: params.maxDescriptionImages,
302
+ maxImageBytes: params.maxImageBytes,
303
+ maxResponseChars: params.maxResponseChars,
304
+ signal,
305
+ });
134
306
  },
135
307
  });
136
308
 
@@ -1,5 +1,11 @@
1
1
  # pi-mono-sentinel
2
2
 
3
+ ## 1.12.0
4
+
5
+ ### Changed
6
+
7
+ - Store project-scoped Sentinel config under the Pi agent directory (`~/.pi/agent/extensions/sentinel/projects/`) instead of creating `.pi/extensions/sentinel.json` in the current working directory. Existing cwd-local config files are still read for compatibility.
8
+
3
9
  ## 1.11.0
4
10
 
5
11
  ### Minor Changes
@@ -14,11 +14,13 @@ It addresses cross-cutting security gaps that pure command-based guardrails miss
14
14
  Sentinel reads and merges optional JSON config from three scopes:
15
15
 
16
16
  1. Global: `$PI_CODING_AGENT_DIR/extensions/sentinel.json` or `~/.pi/agent/extensions/sentinel.json`
17
- 2. Local/project: `.pi/extensions/sentinel.json` under the current working directory
17
+ 2. Local/project: a current-working-directory scoped file under `$PI_CODING_AGENT_DIR/extensions/sentinel/projects/` or `~/.pi/agent/extensions/sentinel/projects/`
18
18
  3. Memory: session-only grants written internally while Pi is running
19
19
 
20
20
  Merge priority is `memory > local > global > defaults`.
21
21
 
22
+ Local/project config is stored in Pi's agent directory instead of the user's working directory, so Sentinel does not create `.pi/` files in arbitrary project folders. Existing legacy `.pi/extensions/sentinel.json` files are still read for compatibility, but new local/project writes go to the agent directory.
23
+
22
24
  ```json
23
25
  {
24
26
  "enabled": true,
@@ -1,7 +1,7 @@
1
1
  import assert from "node:assert/strict";
2
- import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
2
+ import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
3
3
  import { tmpdir } from "node:os";
4
- import { join } from "node:path";
4
+ import { dirname, join } from "node:path";
5
5
  import { afterEach, beforeEach, describe, test } from "node:test";
6
6
 
7
7
  import { SentinelConfigLoader } from "../config.ts";
@@ -39,7 +39,7 @@ describe("SentinelConfigLoader", () => {
39
39
  mkdirSync(join(agentDir, "extensions"), { recursive: true });
40
40
  writeFileSync(loader.getConfigPath("global"), JSON.stringify({ pathAccess: { allowedPaths: ["/global"] } }), { flag: "w" });
41
41
  loader.load(cwd);
42
- mkdirSync(join(cwd, ".pi", "extensions"), { recursive: true });
42
+ mkdirSync(dirname(loader.getConfigPath("local")), { recursive: true });
43
43
  writeFileSync(loader.getConfigPath("local"), JSON.stringify({ features: { pathAccess: true }, pathAccess: { allowedPaths: ["/local"] } }), { flag: "w" });
44
44
  loader.load(cwd);
45
45
  loader.save("memory", { pathAccess: { mode: "block", allowedPaths: ["/memory"] } });
@@ -49,12 +49,26 @@ describe("SentinelConfigLoader", () => {
49
49
  assert.deepEqual(config.pathAccess.allowedPaths, ["/memory"]);
50
50
  });
51
51
 
52
- test("save writes global and local config files", () => {
52
+ test("save writes global and cwd-scoped local config files under the agent dir", () => {
53
53
  const loader = new SentinelConfigLoader();
54
54
  loader.load(cwd);
55
55
  loader.save("global", { enabled: false });
56
56
  loader.save("local", { features: { pathAccess: true } });
57
57
  assert.deepEqual(loader.getRawConfig("global"), { enabled: false });
58
58
  assert.deepEqual(loader.getRawConfig("local"), { features: { pathAccess: true } });
59
+ assert.equal(loader.getConfigPath("local").startsWith(join(agentDir, "extensions", "sentinel", "projects")), true);
60
+ assert.equal(existsSync(join(cwd, ".pi", "extensions", "sentinel.json")), false);
61
+ });
62
+
63
+ test("reads legacy cwd-local config without writing back to cwd", () => {
64
+ const loader = new SentinelConfigLoader();
65
+ mkdirSync(join(cwd, ".pi", "extensions"), { recursive: true });
66
+ writeFileSync(join(cwd, ".pi", "extensions", "sentinel.json"), JSON.stringify({ features: { pathAccess: true } }), { flag: "w" });
67
+
68
+ loader.load(cwd);
69
+ assert.equal(loader.getConfig().features.pathAccess, true);
70
+
71
+ loader.save("local", { pathAccess: { allowedPaths: ["/outside"] } });
72
+ assert.equal(existsSync(loader.getConfigPath("local")), true);
59
73
  });
60
74
  });
@@ -44,7 +44,10 @@ describe("path-access helpers", () => {
44
44
  });
45
45
 
46
46
  test("derives and persists selected path-access grants with the correct scope and target", () => {
47
+ const originalAgentDir = process.env.PI_CODING_AGENT_DIR;
48
+ const agentDir = mkdtempSync(join(tmpdir(), "sentinel-path-access-agent-"));
47
49
  const cwd = mkdtempSync(join(tmpdir(), "sentinel-path-access-cwd-"));
50
+ process.env.PI_CODING_AGENT_DIR = agentDir;
48
51
  try {
49
52
  configLoader.load(cwd);
50
53
  configLoader.save("memory", { features: { pathAccess: true }, pathAccess: { mode: "ask", allowedPaths: [] } });
@@ -69,6 +72,9 @@ describe("path-access helpers", () => {
69
72
  configLoader.addAllowedPath(localFileGrant.scope, localFileGrant.grant);
70
73
  assert.ok(configLoader.getRawConfig("local")?.pathAccess?.allowedPaths?.includes("/tmp/outside-file.txt"));
71
74
  } finally {
75
+ if (originalAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR;
76
+ else process.env.PI_CODING_AGENT_DIR = originalAgentDir;
77
+ rmSync(agentDir, { recursive: true, force: true });
72
78
  rmSync(cwd, { recursive: true, force: true });
73
79
  }
74
80
  });
@@ -1,6 +1,7 @@
1
+ import { createHash } from "node:crypto";
1
2
  import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
3
  import { homedir } from "node:os";
3
- import { dirname, join } from "node:path";
4
+ import { basename, dirname, join, resolve } from "node:path";
4
5
 
5
6
  export type SentinelConfigScope = "global" | "local" | "memory";
6
7
  export type SentinelPathAccessMode = "allow" | "ask" | "block";
@@ -92,6 +93,20 @@ function writeJson(path: string, value: SentinelConfig): void {
92
93
  writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`, "utf-8");
93
94
  }
94
95
 
96
+ function localScopeId(cwd: string): string {
97
+ const normalizedCwd = resolve(cwd);
98
+ const slug = (basename(normalizedCwd) || "root")
99
+ .replace(/[^a-zA-Z0-9._-]+/g, "-")
100
+ .replace(/^-+|-+$/g, "")
101
+ .slice(0, 48) || "root";
102
+ const hash = createHash("sha256").update(normalizedCwd).digest("hex").slice(0, 12);
103
+ return `${slug}-${hash}.json`;
104
+ }
105
+
106
+ function legacyLocalConfigPath(cwd: string): string {
107
+ return join(resolve(cwd), ".pi", "extensions", "sentinel.json");
108
+ }
109
+
95
110
  function isPlainObject(value: unknown): value is Record<string, unknown> {
96
111
  return typeof value === "object" && value !== null && !Array.isArray(value);
97
112
  }
@@ -127,7 +142,11 @@ export class SentinelConfigLoader {
127
142
  load(cwd = process.cwd()): void {
128
143
  this.localCwd = cwd;
129
144
  this.globalConfig = readJson(this.getConfigPath("global"));
130
- this.localConfig = readJson(this.getConfigPath("local"));
145
+ const legacyLocalConfig = readJson(legacyLocalConfigPath(this.localCwd));
146
+ const scopedLocalConfig = readJson(this.getConfigPath("local"));
147
+ this.localConfig = legacyLocalConfig && scopedLocalConfig
148
+ ? mergeConfig(legacyLocalConfig, scopedLocalConfig)
149
+ : scopedLocalConfig ?? legacyLocalConfig;
131
150
  this.resolvedConfig = undefined;
132
151
  }
133
152
 
@@ -152,7 +171,7 @@ export class SentinelConfigLoader {
152
171
  getConfigPath(scope: Exclude<SentinelConfigScope, "memory">): string {
153
172
  return scope === "global"
154
173
  ? join(getAgentDir(), "extensions", "sentinel.json")
155
- : join(this.localCwd, ".pi", "extensions", "sentinel.json");
174
+ : join(getAgentDir(), "extensions", "sentinel", "projects", localScopeId(this.localCwd));
156
175
  }
157
176
 
158
177
  save(scope: SentinelConfigScope, partial: SentinelConfig): void {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-mono-sentinel",
3
- "version": "1.11.0",
3
+ "version": "1.12.0",
4
4
  "description": "Pi extension that guards against content-based secret leaks and indirect script execution",
5
5
  "keywords": [
6
6
  "pi-package",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-mono-all",
3
- "version": "1.2.3",
3
+ "version": "1.2.5",
4
4
  "description": "All pi-mono extensions and bundled skills",
5
5
  "type": "module",
6
6
  "keywords": [
@@ -9,24 +9,24 @@
9
9
  "pi-skill"
10
10
  ],
11
11
  "dependencies": {
12
- "pi-mono-ask-user-question": "1.7.4",
13
12
  "pi-mono-auto-fix": "0.3.1",
13
+ "pi-mono-ask-user-question": "1.7.4",
14
14
  "pi-mono-btw": "1.7.4",
15
- "pi-mono-context": "0.1.1",
16
15
  "pi-mono-clear": "1.7.3",
17
- "pi-mono-figma": "0.2.2",
16
+ "pi-mono-context": "0.1.1",
18
17
  "pi-mono-context-guard": "1.7.3",
19
- "pi-mono-linear": "0.2.3",
18
+ "pi-mono-figma": "0.2.2",
19
+ "pi-common": "0.1.1",
20
+ "pi-mono-linear": "0.2.4",
20
21
  "pi-mono-loop": "1.7.3",
21
- "pi-mono-sentinel": "1.11.0",
22
- "pi-mono-review": "1.8.2",
23
22
  "pi-mono-simplify": "1.7.3",
23
+ "pi-mono-status-line": "1.7.3",
24
+ "pi-mono-sentinel": "1.12.0",
25
+ "pi-mono-review": "1.8.2",
24
26
  "pi-mono-team-mode": "2.3.2",
25
- "pi-mono-multi-edit": "1.7.3",
26
- "pi-common": "0.1.1",
27
+ "pi-mono-usage": "0.1.1",
27
28
  "pi-mono-web-search": "0.1.0",
28
- "pi-mono-status-line": "1.7.3",
29
- "pi-mono-usage": "0.1.1"
29
+ "pi-mono-multi-edit": "1.7.3"
30
30
  },
31
31
  "bundledDependencies": [
32
32
  "pi-mono-ask-user-question",