pi-advisor-flow 0.17.1-dev.1 → 0.17.1-dev.3

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/locales/fr.json CHANGED
@@ -333,5 +333,7 @@
333
333
  "usage.call": "appel",
334
334
  "usage.calls": "appels",
335
335
  "usage.unavailable": "indisponible",
336
- "usage.withoutData": "sans données d'utilisation"
336
+ "usage.withoutData": "sans données d'utilisation",
337
+ "jevSetup.providerKeyRestored": "Fournisseur vérifié, mais les réglages n'ont pas pu être enregistrés ; la clé précédente a été restaurée.",
338
+ "jevSetup.providerKeyNotRestored": "Fournisseur vérifié, mais les réglages n'ont pas pu être enregistrés et la clé précédente n'a pas pu être restaurée. Saisissez une clé valide avant de réessayer."
337
339
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-advisor-flow",
3
- "version": "0.17.1-dev.1",
3
+ "version": "0.17.1-dev.3",
4
4
  "description": "Advanced Executor/Advisor flow for Pi, fully configurable and extendable.",
5
5
  "keywords": [
6
6
  "advisor",
@@ -62,18 +62,18 @@
62
62
  "format:check": "bun fmt --no-script --print-width 80 --trailing-comma es5 --sort-imports --bracket-same-line --ignore-pattern 'bench/tasks/**/traps.toml' --ignore-pattern 'dist/**' --check"
63
63
  },
64
64
  "devDependencies": {
65
- "@earendil-works/pi-ai": "1.6.0",
66
- "@earendil-works/pi-coding-agent": "1.6.0",
67
- "@earendil-works/pi-tui": "1.6.0",
65
+ "@earendil-works/pi-ai": "1.6.1",
66
+ "@earendil-works/pi-coding-agent": "1.6.1",
67
+ "@earendil-works/pi-tui": "1.6.1",
68
68
  "@juicesharp/rpiv-i18n": "2.15.0",
69
- "@oxlint/plugins": "1.94.0",
70
- "@types/node": "^26.6.6",
69
+ "@oxlint/plugins": "1.95.0",
70
+ "@types/node": "^26.6.11",
71
71
  "@typesafe-ai/sdk": "^0.7.0",
72
72
  "bun-types": "1.4.5",
73
73
  "husky": "^9.1.7",
74
- "knip": "6.47.0",
75
- "lint-staged": "^17.6.1",
76
- "oxlint": "1.94.0",
74
+ "knip": "6.48.0",
75
+ "lint-staged": "^17.6.2",
76
+ "oxlint": "1.95.0",
77
77
  "typebox": "1.4.7",
78
78
  "typescript": "^7.0.2",
79
79
  "ultracite": "8.3.1"
@@ -110,7 +110,7 @@
110
110
  "safe-buffer": "npm:@socketregistry/safe-buffer@1.0.9",
111
111
  "undici": "8.12.2"
112
112
  },
113
- "packageManager": "bun@1.4.4",
113
+ "packageManager": "bun@1.4.5",
114
114
  "pi": {
115
115
  "extensions": [
116
116
  "./dist/index.js"
@@ -66,7 +66,7 @@ if (
66
66
  !isAtLeast(currentVersion, minimumVersion)
67
67
  ) {
68
68
  console.error(
69
- `This repository requires Bun ${minimumVersion ?? "1.4.4"} or newer; found ${currentVersion ?? "a non-Bun package manager"}.`
69
+ `This repository requires Bun ${minimumVersion ?? "1.4.5"} or newer; found ${currentVersion ?? "a non-Bun package manager"}.`
70
70
  );
71
71
  process.exitCode = 1;
72
72
  } else {
@@ -72,48 +72,55 @@ export const repositoryRoot = (cwd: string) => {
72
72
  }
73
73
  };
74
74
 
75
- const untracked = (cwd: string, path: string) => {
76
- const output = git(cwd, [
77
- "ls-files",
78
- "--others",
79
- "--exclude-standard",
80
- "-z",
81
- "--",
82
- path,
83
- ]);
84
-
85
- const expected = normalizeRelativePath(cwd, path);
86
-
87
- return output
88
- .split("\0")
89
- .filter(Boolean)
90
- .some((entry) => normalizeRelativePath(cwd, entry) === expected);
91
- };
75
+ const MEMBERSHIP_QUERY_BATCH = 256;
92
76
 
93
- const tracked = (cwd: string, path: string) => {
94
- const output = git(cwd, ["ls-files", "--stage", "-z", "--", path]);
95
- const expected = normalizeRelativePath(cwd, path);
77
+ const normalizeAll = (root: string, paths: readonly string[]) =>
78
+ new Set(paths.map((path) => normalizeRelativePath(root, path)));
96
79
 
97
- return output.split("\0").some((entry) => {
98
- if (!entry) {
99
- return false;
100
- }
80
+ export const permittedPaths = (
81
+ root: string,
82
+ paths: readonly string[],
83
+ kind: "tracked" | "untracked"
84
+ ): Set<string> => {
85
+ const wanted = normalizeAll(root, paths);
86
+ const permitted = new Set<string>();
87
+
88
+ for (let start = 0; start < paths.length; start += MEMBERSHIP_QUERY_BATCH) {
89
+ const batch = paths.slice(start, start + MEMBERSHIP_QUERY_BATCH);
90
+
91
+ const output =
92
+ kind === "tracked"
93
+ ? git(root, ["ls-files", "--stage", "-z", "--", ...batch])
94
+ : git(root, [
95
+ "ls-files",
96
+ "--others",
97
+ "--exclude-standard",
98
+ "-z",
99
+ "--",
100
+ ...batch,
101
+ ]);
102
+
103
+ for (const entry of output.split("\0")) {
104
+ if (!entry) {
105
+ continue;
106
+ }
101
107
 
102
- const [metadata, name] = entry.split("\t");
108
+ const name = kind === "tracked" ? (entry.split("\t")[1] ?? "") : entry;
103
109
 
104
- return (
105
- name &&
106
- normalizeRelativePath(cwd, name) === expected &&
107
- !metadata.startsWith("160000 ")
108
- );
109
- });
110
- };
110
+ if (kind === "tracked" && entry.startsWith("160000 ")) {
111
+ continue;
112
+ }
111
113
 
112
- export const isPermitted = (
113
- root: string,
114
- path: string,
115
- kind: "tracked" | "untracked"
116
- ) => (kind === "tracked" ? tracked(root, path) : untracked(root, path));
114
+ const normalized = normalizeRelativePath(root, name);
115
+
116
+ if (wanted.has(normalized)) {
117
+ permitted.add(normalized);
118
+ }
119
+ }
120
+ }
121
+
122
+ return permitted;
123
+ };
117
124
 
118
125
  const readAttachment = async (
119
126
  root: string,
@@ -193,8 +200,6 @@ const readFiles = async (
193
200
  }
194
201
 
195
202
  const unique = new Set<string>();
196
- const attachments: UntrackedAttachment[] = [];
197
- let total = 0;
198
203
 
199
204
  for (const name of requested) {
200
205
  const normalizedName = normalizeRequestedPath(root, name);
@@ -208,9 +213,22 @@ const readFiles = async (
208
213
  }
209
214
 
210
215
  unique.add(normalizedName);
216
+ }
217
+
218
+ let permitted: Set<string>;
219
+
220
+ try {
221
+ permitted = permittedPaths(root, [...unique], kind);
222
+ } catch {
223
+ return [];
224
+ }
225
+
226
+ const attachments: UntrackedAttachment[] = [];
227
+ let total = 0;
211
228
 
229
+ for (const normalizedName of unique) {
212
230
  try {
213
- if (!isPermitted(root, normalizedName, kind)) {
231
+ if (!permitted.has(normalizedName)) {
214
232
  continue;
215
233
  }
216
234
 
@@ -95,7 +95,9 @@ const resolveActivationModels = async (
95
95
  };
96
96
  }
97
97
 
98
- return {};
98
+ return {
99
+ switchedExecutor: Boolean(executor) && !isMarkedSubagent(),
100
+ };
99
101
  };
100
102
 
101
103
  const restoreActivationRefsIfCurrent = (
@@ -145,11 +147,12 @@ const restoreActivationRefs = (
145
147
  }
146
148
  };
147
149
 
148
- const persistSuccessfulActivation = (
150
+ const persistSuccessfulActivation = async (
149
151
  ctx: ExtensionContext,
150
152
  shouldSave: boolean,
151
153
  reenableTools: boolean,
152
- restoreRefs: () => void
154
+ restoreRefs: () => void,
155
+ restoreHostModel: () => Promise<boolean>
153
156
  ) => {
154
157
  if (!shouldSave) {
155
158
  return true;
@@ -159,11 +162,13 @@ const persistSuccessfulActivation = (
159
162
  saveConfig(ctx, { persistAdvisor: true, persistExecutor: true });
160
163
  } catch (saveError) {
161
164
  if (!reenableTools) {
165
+ await restoreHostModel();
162
166
  throw saveError;
163
167
  }
164
168
 
165
169
  setAdvisorToolsEnabledRef(false);
166
170
  restoreRefs();
171
+ await restoreHostModel();
167
172
 
168
173
  const message =
169
174
  saveError instanceof Error ? saveError.message : String(saveError);
@@ -209,9 +214,9 @@ export const activateAdvisor = async (
209
214
  args: string,
210
215
  ctx: ExtensionContext,
211
216
  announce = true
212
- ) => {
217
+ ): Promise<boolean> => {
213
218
  if (!loadCommandConfig(ctx)) {
214
- return;
219
+ return false;
215
220
  }
216
221
 
217
222
  const { toolAvailabilityRevision } = runtime;
@@ -234,9 +239,12 @@ export const activateAdvisor = async (
234
239
  restoreRefs(attempted);
235
240
  notify(ctx, argumentError, "error");
236
241
 
237
- return;
242
+ return false;
238
243
  }
239
244
 
245
+ // parseArgs mutates the refs; refresh so a later failure rolls them back.
246
+ attempted = liveRefSnapshot();
247
+
240
248
  const prepared = await prepareActivationModels(
241
249
  runtime,
242
250
  ctx,
@@ -250,24 +258,26 @@ export const activateAdvisor = async (
250
258
  attempted = liveRefSnapshot();
251
259
  restoreActivationRefsIfCurrent(canContinue, () => restoreRefs(attempted));
252
260
 
253
- return;
261
+ return false;
254
262
  }
255
263
 
256
- const { cancelled, error } = await resolveActivationModels(
264
+ const entryModel = ctx.model;
265
+
266
+ const { cancelled, error, switchedExecutor } = await resolveActivationModels(
257
267
  runtime,
258
268
  ctx,
259
269
  canContinue
260
270
  );
261
271
 
262
272
  if (cancelled || !canContinue()) {
263
- return;
273
+ return false;
264
274
  }
265
275
 
266
276
  if (error) {
267
277
  restoreRefs(attempted);
268
278
  notify(ctx, error, "error");
269
279
 
270
- return;
280
+ return false;
271
281
  }
272
282
 
273
283
  // Persist model changes only after both models are known and authenticated.
@@ -282,12 +292,21 @@ export const activateAdvisor = async (
282
292
  !sessionScoped &&
283
293
  Boolean(args.trim() || prepared.pickedModels || reenableTools);
284
294
 
295
+ const restoreHostModel = () =>
296
+ switchedExecutor && entryModel
297
+ ? runtime.setExecutorModel(entryModel)
298
+ : Promise.resolve(false);
299
+
285
300
  if (
286
- !persistSuccessfulActivation(ctx, shouldSave, reenableTools, () =>
287
- restoreRefs(liveRefSnapshot())
288
- )
301
+ !(await persistSuccessfulActivation(
302
+ ctx,
303
+ shouldSave,
304
+ reenableTools,
305
+ () => restoreRefs(liveRefSnapshot()),
306
+ restoreHostModel
307
+ ))
289
308
  ) {
290
- return;
309
+ return false;
291
310
  }
292
311
 
293
312
  if (executorEffortRef && !isMarkedSubagent()) {
@@ -312,4 +331,6 @@ export const activateAdvisor = async (
312
331
  if (announce) {
313
332
  announceActivation(ctx, activeModel);
314
333
  }
334
+
335
+ return true;
315
336
  };
@@ -16,7 +16,7 @@ export type ActivateAdvisor = (
16
16
  args: string,
17
17
  ctx: ExtensionContext,
18
18
  announce?: boolean
19
- ) => Promise<void>;
19
+ ) => Promise<boolean>;
20
20
 
21
21
  export const registerCommandLifecycle = (
22
22
  runtime: CommandRuntime,
@@ -47,8 +47,15 @@ export const registerCommandLifecycle = (
47
47
  }
48
48
 
49
49
  if (alwaysOnRef) {
50
- setAdvisorToolsActive(runtime.pi, false);
51
- await activateAdvisor("", ctx, false);
50
+ const { toolAvailabilityRevision } = runtime;
51
+ const activated = await activateAdvisor("", ctx, false);
52
+
53
+ if (
54
+ !activated &&
55
+ runtime.toolAvailabilityRevision === toolAvailabilityRevision
56
+ ) {
57
+ setAdvisorToolsActive(runtime.pi, false);
58
+ }
52
59
  } else {
53
60
  runtime.updateSameModelNotice(ctx);
54
61
  }
@@ -32,7 +32,9 @@ export const registerModelCommands = (runtime: CommandRuntime) => {
32
32
  runtime.pi.registerCommand("advisor", {
33
33
  description:
34
34
  "Enable the Executor/Advisor flow and switch to the configured or explicitly selected Executor model; accepts contextMaxChars=N",
35
- handler: (args, ctx) => activateAdvisor(runtime, args, ctx),
35
+ handler: async (args, ctx) => {
36
+ await activateAdvisor(runtime, args, ctx);
37
+ },
36
38
  });
37
39
 
38
40
  runtime.pi.registerCommand("advisor-models", {
@@ -167,7 +167,10 @@ export const saveAdvisorSettings = (
167
167
  persistExecutor: Boolean(persisted.executor),
168
168
  });
169
169
 
170
- if (!options.skipOutcomeLogging) {
170
+ if (
171
+ !options.skipOutcomeLogging &&
172
+ (settings.outcomeLogging ?? false) !== previous.outcomeLogging
173
+ ) {
171
174
  saveGlobalOutcomeLogging(settings.outcomeLogging ?? false);
172
175
  }
173
176
 
@@ -5,6 +5,7 @@ import {
5
5
  GATE_FAILURE_MODES,
6
6
  JEV_TRANSPORTS,
7
7
  MAX_CONTEXT_MAX_CHARS,
8
+ MAX_JEV_TIMEOUT_MS,
8
9
  MAX_SCOUT_TIMEOUT_MS,
9
10
  TRACKED_FILE_HANDOFF_MODES,
10
11
  } from "./types.ts";
@@ -74,7 +75,10 @@ export const isValidToolResultMaxBytes = (value: unknown): value is number =>
74
75
  isValidNonNegativeSafeInteger(value);
75
76
 
76
77
  export const isValidJevTimeoutMs = (value: unknown): value is number =>
77
- typeof value === "number" && Number.isSafeInteger(value) && value >= 1;
78
+ typeof value === "number" &&
79
+ Number.isSafeInteger(value) &&
80
+ value >= 1 &&
81
+ value <= MAX_JEV_TIMEOUT_MS;
78
82
 
79
83
  export const isValidScoutTimeoutMs = (value: unknown): value is number =>
80
84
  typeof value === "number" &&
@@ -87,6 +87,7 @@ import {
87
87
  GATE_FAILURE_MODES,
88
88
  JEV_TRANSPORTS,
89
89
  MAX_CONTEXT_MAX_CHARS,
90
+ MAX_JEV_TIMEOUT_MS,
90
91
  MAX_SCOUT_TIMEOUT_MS,
91
92
  TRACKED_FILE_HANDOFF_MODES,
92
93
  } from "./types.ts";
@@ -289,7 +290,7 @@ export const CONFIG_SCHEMA = {
289
290
  validate: isValidJevPricePerMtok,
290
291
  },
291
292
  advisorJevTimeoutMs: {
292
- accepted: "a positive safe integer",
293
+ accepted: `a positive safe integer no greater than ${MAX_JEV_TIMEOUT_MS} milliseconds`,
293
294
  current: () => advisorJevTimeoutMsRef,
294
295
  persisted: true,
295
296
  type: "number",
@@ -318,6 +318,7 @@ export const saveConfig = (
318
318
  return path;
319
319
  }
320
320
 
321
+ const identity = configFileIdentity(path);
321
322
  const existing = readConfigForSave(path);
322
323
 
323
324
  const data = applyChangedConfigValues(
@@ -328,7 +329,7 @@ export const saveConfig = (
328
329
  persistExecutor
329
330
  );
330
331
 
331
- writeFileSync(path, `${JSON.stringify(data, null, 2)}\n`);
332
+ writeConfigAtomically(path, `${JSON.stringify(data, null, 2)}\n`, identity);
332
333
  resetConfigCache();
333
334
  const nextLoadedState = { ...current };
334
335
 
@@ -399,6 +400,23 @@ const writeConfigAtomically = (
399
400
  }
400
401
  };
401
402
 
403
+ export const removeConfigKeys = (keys: readonly string[]) => {
404
+ const path = join(getAgentDir(), "advisor.json");
405
+ const identity = configFileIdentity(path);
406
+ const existing = readConfigForSave(path);
407
+
408
+ const retained = Object.fromEntries(
409
+ Object.entries(existing).filter(([key]) => !keys.includes(key))
410
+ );
411
+
412
+ writeConfigAtomically(
413
+ path,
414
+ `${JSON.stringify(retained, null, 2)}\n`,
415
+ identity
416
+ );
417
+ resetConfigCache();
418
+ };
419
+
402
420
  /** Outcome logging is deliberately written only to the global Pi configuration. */
403
421
  export const saveGlobalOutcomeLogging = (
404
422
  enabled: boolean | null,
@@ -24,6 +24,7 @@ export const JEV_API_KEY_CLASSIFIER = "jev-api-key";
24
24
  export const DEFAULT_JEV_TIMEOUT_MS = 8000;
25
25
  export const DEFAULT_SCOUT_TIMEOUT_MS = 30_000;
26
26
  export const MAX_SCOUT_TIMEOUT_MS = 2_147_483_647;
27
+ export const MAX_JEV_TIMEOUT_MS = 2_147_483_647;
27
28
  export const DEFAULT_JEV_DIGEST_MAX_CHARS = 4000;
28
29
  export const DEFAULT_JEV_PRICE_PER_MTOK = 0.042;
29
30
  export const DEFAULT_JEV_FILTER_SKIP_CONFIDENCE = 0.85;
package/src/git.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { execFileSync } from "node:child_process";
1
+ import { execFile } from "node:child_process";
2
2
 
3
3
  import { isString } from "./content-utils.ts";
4
4
 
@@ -77,7 +77,51 @@ const EMPTY_TREE = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";
77
77
  const GIT_TOTAL_TIMEOUT_MS = 5000;
78
78
  const GIT_MAX_BUFFER = 16 * 1024 * 1024;
79
79
 
80
- export type GitRunner = (args: string[], cwd: string) => string;
80
+ export type GitRunner = (args: string[], cwd: string) => Promise<string>;
81
+
82
+ interface GitExecOptions {
83
+ cwd: string;
84
+ encoding: "utf-8";
85
+ maxBuffer: number;
86
+ shell: false;
87
+ timeout: number;
88
+ windowsHide: boolean;
89
+ }
90
+
91
+ // SAFETY: execFile is callback-based; this adapter resolves exactly once.
92
+ const execFileText = (
93
+ file: string,
94
+ args: readonly string[],
95
+ options: GitExecOptions
96
+ ): Promise<string> =>
97
+ new Promise<string>((resolve, reject) => {
98
+ // SAFETY: execFile accepts the readonly argument list without mutation.
99
+ execFile(
100
+ file,
101
+ args as string[],
102
+ options,
103
+ (error: Error | null, stdout: string | Buffer) => {
104
+ if (error) {
105
+ reject(error);
106
+
107
+ return;
108
+ }
109
+
110
+ resolve(String(stdout));
111
+ }
112
+ );
113
+ });
114
+
115
+ // Never use a shell: arguments are fixed and must not be re-parsed.
116
+ const execGit = (args: string[], cwd: string, timeoutMs: number) =>
117
+ execFileText("git", args, {
118
+ cwd,
119
+ encoding: "utf-8",
120
+ maxBuffer: GIT_MAX_BUFFER,
121
+ shell: false,
122
+ timeout: timeoutMs,
123
+ windowsHide: true,
124
+ });
81
125
 
82
126
  /** Shares one deadline across commands so a pathological repository cannot block for the sum of per-command timeouts. */
83
127
  const deadlineRunner = (): GitRunner => {
@@ -90,23 +134,14 @@ const deadlineRunner = (): GitRunner => {
90
134
  throw new Error("Git context collection exceeded its time budget.");
91
135
  }
92
136
 
93
- return execFileSync("git", args, {
94
- cwd,
95
- encoding: "utf-8",
96
- maxBuffer: GIT_MAX_BUFFER,
97
- // Never use a shell: arguments are fixed and must not be re-parsed.
98
- shell: false,
99
- stdio: ["ignore", "pipe", "pipe"],
100
- timeout: remaining,
101
- windowsHide: true,
102
- });
137
+ return execGit(args, cwd, remaining);
103
138
  };
104
139
  };
105
140
 
106
141
  /** Resolves the base revision, falling back to the empty tree before any commit. */
107
- const diffBase = (run: GitRunner, cwd: string): string => {
142
+ const diffBase = async (run: GitRunner, cwd: string): Promise<string> => {
108
143
  try {
109
- run(["rev-parse", "--verify", "--quiet", "HEAD"], cwd);
144
+ await run(["rev-parse", "--verify", "--quiet", "HEAD"], cwd);
110
145
 
111
146
  return "HEAD";
112
147
  } catch {
@@ -115,19 +150,19 @@ const diffBase = (run: GitRunner, cwd: string): string => {
115
150
  };
116
151
 
117
152
  /** Collects staged and unstaged changes vs HEAD; summary omits diff hunk headers because git derives them from untouched lines that can reproduce secrets. */
118
- export const collectGitContext = (
153
+ export const collectGitContext = async (
119
154
  cwd: string,
120
155
  level: GitContextLevel,
121
156
  maxChars: number,
122
157
  redact: (value: string) => string = (value) => value,
123
158
  run: GitRunner = deadlineRunner()
124
- ): GitContextResult => {
159
+ ): Promise<GitContextResult> => {
125
160
  if (level === "off" || maxChars <= 0) {
126
161
  return { level: "off", status: "disabled", text: "" };
127
162
  }
128
163
 
129
164
  try {
130
- run(["rev-parse", "--is-inside-work-tree"], cwd);
165
+ await run(["rev-parse", "--is-inside-work-tree"], cwd);
131
166
  } catch (error) {
132
167
  return {
133
168
  detail: error instanceof Error ? error.message : String(error),
@@ -138,14 +173,18 @@ export const collectGitContext = (
138
173
  }
139
174
 
140
175
  try {
141
- const base = diffBase(run, cwd);
142
- const nameStatus = run(["diff", "--name-status", base], cwd).trim();
143
- const shortstat = run(["diff", "--shortstat", base], cwd).trim();
176
+ const base = await diffBase(run, cwd);
177
+ const nameStatusOutput = await run(["diff", "--name-status", base], cwd);
178
+ const shortstatOutput = await run(["diff", "--shortstat", base], cwd);
144
179
 
145
- const untracked = run(
180
+ const untrackedOutput = await run(
146
181
  ["ls-files", "--others", "--exclude-standard"],
147
182
  cwd
148
- ).trim();
183
+ );
184
+
185
+ const nameStatus = nameStatusOutput.trim();
186
+ const shortstat = shortstatOutput.trim();
187
+ const untracked = untrackedOutput.trim();
149
188
 
150
189
  if (!(nameStatus || untracked)) {
151
190
  return { level, status: "no-changes", text: "" };
@@ -161,7 +200,7 @@ export const collectGitContext = (
161
200
  ];
162
201
 
163
202
  if (level === "full") {
164
- const patch = run(["diff", base], cwd);
203
+ const patch = await run(["diff", base], cwd);
165
204
  sections.push(
166
205
  patch.trim()
167
206
  ? `Patch:\n${patch}`
@@ -7,8 +7,8 @@ import type { ImageContent } from "@earendil-works/pi-ai/compat";
7
7
  import {
8
8
  imageFileCandidate,
9
9
  imageMime,
10
- isPermitted,
11
10
  normalizeRequestedPath,
11
+ permittedPaths,
12
12
  repositoryRoot,
13
13
  within,
14
14
  } from "./attachments.ts";
@@ -104,30 +104,46 @@ export const readImageFiles = async (
104
104
  }
105
105
 
106
106
  const seen = new Set<string>();
107
- const images: ImageAttachment[] = [];
108
- let omitted = 0;
109
- let bytes = 0;
107
+ const candidates: { mime: string; name: string }[] = [];
110
108
 
111
109
  for (const path of names) {
112
110
  const name = normalizeRequestedPath(root, path);
113
111
 
114
- if (name && seen.has(name)) {
112
+ if (!name || seen.has(name)) {
115
113
  continue;
116
114
  }
117
115
 
118
- if (name) {
119
- seen.add(name);
116
+ seen.add(name);
117
+
118
+ const mime = imageMime(name);
119
+
120
+ if (mime) {
121
+ candidates.push({ mime, name });
120
122
  }
123
+ }
121
124
 
122
- try {
123
- const mime = name && imageMime(name);
125
+ let permitted: Set<string>;
126
+
127
+ try {
128
+ permitted = permittedPaths(
129
+ root,
130
+ candidates.map((candidate) => candidate.name),
131
+ kind
132
+ );
133
+ } catch {
134
+ return { images: [], omitted: names.length };
135
+ }
124
136
 
137
+ const images: ImageAttachment[] = [];
138
+ let omitted = names.length - candidates.length;
139
+ let bytes = 0;
140
+
141
+ for (const { mime, name } of candidates) {
142
+ try {
125
143
  const image =
126
- name &&
127
- mime &&
128
144
  images.length < remainingCount &&
129
145
  remainingBytes - bytes > 0 &&
130
- isPermitted(root, name, kind)
146
+ permitted.has(name)
131
147
  ? await readImageAttachment(root, name, mime, remainingBytes - bytes)
132
148
  : undefined;
133
149