pi-advisor-flow 0.13.1 → 0.13.2-dev.1

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 (105) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/dist/index.js +14 -7
  3. package/extensions/index.ts +6 -0
  4. package/package.json +9 -9
  5. package/scripts/check-bun-version.mjs +9 -0
  6. package/src/attachments.ts +36 -0
  7. package/src/child-session.ts +1 -0
  8. package/src/commands/activation-preparation.ts +12 -0
  9. package/src/commands/activation.ts +43 -0
  10. package/src/commands/advisor-tools.ts +3 -0
  11. package/src/commands/lifecycle.ts +15 -0
  12. package/src/commands/manual-command.ts +19 -0
  13. package/src/commands/manual-consultation.ts +20 -0
  14. package/src/commands/manual-progress.ts +13 -0
  15. package/src/commands/model-commands.ts +4 -0
  16. package/src/commands/model-options.ts +18 -0
  17. package/src/commands/model-picker.ts +16 -0
  18. package/src/commands/outcome-stats.ts +9 -0
  19. package/src/commands/registration.ts +1 -0
  20. package/src/commands/renderers.ts +14 -0
  21. package/src/commands/runtime.ts +5 -0
  22. package/src/commands/settings-commands.ts +18 -0
  23. package/src/commands/settings-persistence.ts +2 -0
  24. package/src/commands.ts +1 -0
  25. package/src/config/args.ts +7 -0
  26. package/src/config/defaults.ts +1 -0
  27. package/src/config/schema.ts +1 -0
  28. package/src/config/state.ts +64 -1
  29. package/src/config/storage.ts +37 -0
  30. package/src/config/types.ts +9 -0
  31. package/src/config/validation.ts +7 -0
  32. package/src/config.ts +6 -0
  33. package/src/content-utils.ts +5 -0
  34. package/src/conversation.ts +39 -0
  35. package/src/follow-up.ts +8 -0
  36. package/src/git.ts +8 -0
  37. package/src/herdr-block.ts +7 -0
  38. package/src/herdr-shared.ts +23 -0
  39. package/src/herdr.ts +18 -0
  40. package/src/image-attachments.ts +24 -0
  41. package/src/image-validation.ts +58 -0
  42. package/src/images.ts +24 -0
  43. package/src/jev/base-url.ts +14 -0
  44. package/src/jev/client.ts +49 -0
  45. package/src/jev/decisions-client.ts +14 -0
  46. package/src/jev/decisions-response.ts +38 -0
  47. package/src/jev/endpoint-key-store.ts +18 -0
  48. package/src/jev/key-store.ts +28 -0
  49. package/src/jev/ledger.ts +30 -12
  50. package/src/jev/openai-key-store.ts +17 -0
  51. package/src/jev/questions.ts +15 -0
  52. package/src/jev/state.ts +5 -0
  53. package/src/jev/transport.ts +35 -0
  54. package/src/model-stream.ts +32 -0
  55. package/src/outcome-stats.ts +16 -0
  56. package/src/outcomes.ts +31 -0
  57. package/src/pi-settings.ts +9 -0
  58. package/src/preferences.ts +26 -0
  59. package/src/redaction.ts +8 -0
  60. package/src/scout-context.ts +17 -0
  61. package/src/scout-curation.ts +12 -0
  62. package/src/scout-groups.ts +47 -0
  63. package/src/scout-protocol.ts +17 -0
  64. package/src/scout-reconstruct.ts +12 -0
  65. package/src/scout.ts +47 -0
  66. package/src/session-context.ts +11 -0
  67. package/src/session-state.ts +73 -13
  68. package/src/tool-result-cap.ts +11 -0
  69. package/src/tools/consult-context.ts +24 -0
  70. package/src/tools/consultation.ts +43 -0
  71. package/src/tools/gate-policy.ts +18 -0
  72. package/src/tools/gate-protocol.ts +22 -0
  73. package/src/tools/jev-filter.ts +26 -0
  74. package/src/tools/jev-turn-gate.ts +17 -0
  75. package/src/tools/loop-gate.ts +25 -0
  76. package/src/tools/model-access.ts +12 -0
  77. package/src/tools/outage-notifier.ts +4 -0
  78. package/src/tools/prompts.ts +17 -0
  79. package/src/tools/register-ask-advisor.ts +44 -0
  80. package/src/tools/register-lifecycle.ts +32 -0
  81. package/src/tools/register-outcome.ts +7 -0
  82. package/src/tools/register-renderers.ts +14 -0
  83. package/src/tools/registration.ts +3 -0
  84. package/src/tools/render-advisor-result.ts +44 -0
  85. package/src/tools/render-common.ts +10 -0
  86. package/src/tools/scout-status.ts +34 -0
  87. package/src/tools/session.ts +3 -0
  88. package/src/tools.ts +8 -0
  89. package/src/ui/jev-filter-submenu.ts +21 -0
  90. package/src/ui/jev-provider-submenu-view.ts +22 -0
  91. package/src/ui/jev-provider-submenu.ts +81 -0
  92. package/src/ui/jev-setup-support.ts +26 -0
  93. package/src/ui/manual-dialog-render.ts +20 -0
  94. package/src/ui/manual-dialog.ts +38 -0
  95. package/src/ui/masked-input.ts +2 -0
  96. package/src/ui/searchable-model-list.ts +28 -0
  97. package/src/ui/settings-formatting.ts +26 -0
  98. package/src/ui/settings-items.ts +11 -0
  99. package/src/ui/settings-list-adapter.ts +13 -0
  100. package/src/ui/settings-mutations.ts +60 -0
  101. package/src/ui/settings-selector.ts +30 -0
  102. package/src/ui/text-setting-submenu.ts +9 -0
  103. package/src/ui-guard.ts +1 -0
  104. package/src/ui.ts +3 -0
  105. package/src/usage.ts +31 -0
@@ -40,14 +40,17 @@ export type HerdrRequest = HerdrMetadataRequest | HerdrNotificationRequest;
40
40
  export type Report = (request: HerdrRequest) => void;
41
41
 
42
42
  let sequence = Date.now() * 1000;
43
+
43
44
  export const nextSequence = () => {
44
45
  sequence += 1;
46
+
45
47
  return sequence;
46
48
  };
47
49
 
48
50
  // Herdr drops socket reports from other sources, so the blocked state must be
49
51
  // signalled through the in-process pi event bus its integration listens on.
50
52
  type BlockedEmitter = (active: boolean, label: string) => void;
53
+
51
54
  let emitBlocked: BlockedEmitter | undefined;
52
55
 
53
56
  export const setHerdrBlockedEmitter = (emitter: BlockedEmitter | undefined) => {
@@ -114,10 +117,13 @@ const sendRequestAttempt = (
114
117
  if (settled) {
115
118
  return;
116
119
  }
120
+
117
121
  settled = true;
122
+
118
123
  if (timeout) {
119
124
  clearTimeout(timeout);
120
125
  }
126
+
121
127
  socket?.destroy();
122
128
  deferred.resolve({ responded, wrote });
123
129
  };
@@ -126,6 +132,7 @@ const sendRequestAttempt = (
126
132
  socket = net.createConnection(endpoint);
127
133
  socket.once("connect", () => {
128
134
  wrote = true;
135
+
129
136
  try {
130
137
  socket?.write(`${JSON.stringify(request)}\n`);
131
138
  } catch {
@@ -141,6 +148,7 @@ const sendRequestAttempt = (
141
148
  } catch {
142
149
  finish(false);
143
150
  }
151
+
144
152
  return deferred.promise;
145
153
  };
146
154
 
@@ -150,12 +158,15 @@ const sendQueuedReport = async ({ endpoint, request }: QueuedReport) => {
150
158
  request,
151
159
  FIRST_ATTEMPT_TIMEOUT_MS
152
160
  );
161
+
153
162
  if (first.responded) {
154
163
  return;
155
164
  }
165
+
156
166
  if (!isMetadataRequest(request) && first.wrote) {
157
167
  return;
158
168
  }
169
+
159
170
  await sendRequestAttempt(endpoint, request, RETRY_ATTEMPT_TIMEOUT_MS);
160
171
  };
161
172
 
@@ -163,10 +174,13 @@ const drainReportQueue = async (key: string, queue: ReportQueue) => {
163
174
  if (queue.active) {
164
175
  return;
165
176
  }
177
+
166
178
  queue.active = true;
179
+
167
180
  try {
168
181
  while (queue.reports.length > 0) {
169
182
  const report = queue.reports.shift();
183
+
170
184
  if (report) {
171
185
  try {
172
186
  await sendQueuedReport(report);
@@ -177,6 +191,7 @@ const drainReportQueue = async (key: string, queue: ReportQueue) => {
177
191
  }
178
192
  } finally {
179
193
  queue.active = false;
194
+
180
195
  if (queue.reports.length === 0) {
181
196
  reportQueues.delete(key);
182
197
  } else {
@@ -188,10 +203,12 @@ const drainReportQueue = async (key: string, queue: ReportQueue) => {
188
203
  const enqueueReport = (report: QueuedReport) => {
189
204
  const key = reportQueueKey(report.request);
190
205
  let queue = reportQueues.get(key);
206
+
191
207
  if (!queue) {
192
208
  queue = { active: false, reports: [] };
193
209
  reportQueues.set(key, queue);
194
210
  }
211
+
195
212
  if (isMetadataRequest(report.request)) {
196
213
  if (queue.active) {
197
214
  queue.reports = [report];
@@ -202,8 +219,10 @@ const enqueueReport = (report: QueuedReport) => {
202
219
  if (queue.reports.length >= MAX_PENDING_NOTIFICATIONS) {
203
220
  return;
204
221
  }
222
+
205
223
  queue.reports.push(report);
206
224
  }
225
+
207
226
  if (!queue.active) {
208
227
  void drainReportQueue(key, queue);
209
228
  }
@@ -213,13 +232,17 @@ export const sendToHerdr: Report = (request) => {
213
232
  if (process.env.HERDR_ENV !== "1") {
214
233
  return;
215
234
  }
235
+
216
236
  const paneId = process.env.HERDR_PANE_ID;
217
237
  const socketPath = process.env.HERDR_SOCKET_PATH;
238
+
218
239
  if (!(paneId && socketPath)) {
219
240
  return;
220
241
  }
242
+
221
243
  const endpoint =
222
244
  process.platform === "win32" ? `\\\\.\\pipe\\${socketPath}` : socketPath;
245
+
223
246
  enqueueReport({ endpoint, request });
224
247
  };
225
248
 
package/src/herdr.ts CHANGED
@@ -10,6 +10,7 @@ import {
10
10
  } from "./herdr-shared.ts";
11
11
 
12
12
  export { HerdrAdvisorBlock } from "./herdr-block.ts";
13
+
13
14
  export {
14
15
  createHerdrNotificationRequest,
15
16
  type HerdrMetadataRequest,
@@ -66,6 +67,7 @@ export class HerdrAdvisorActivity implements HerdrAdvisorActivityScope {
66
67
 
67
68
  createScope(): HerdrAdvisorActivityScope {
68
69
  const owner = Symbol("Herdr Advisor runtime");
70
+
69
71
  return {
70
72
  clear: () => this.clearFor(owner),
71
73
  start: () => this.startFor(owner),
@@ -74,24 +76,31 @@ export class HerdrAdvisorActivity implements HerdrAdvisorActivityScope {
74
76
 
75
77
  private startFor(owner: symbol) {
76
78
  const lease = Symbol("Herdr activity lease");
79
+
77
80
  if (!this.enabled()) {
78
81
  return () => this.finishLease(owner, lease);
79
82
  }
83
+
80
84
  let leases = this.#activeByOwner.get(owner);
85
+
81
86
  if (!leases) {
82
87
  leases = new Set();
83
88
  this.#activeByOwner.set(owner, leases);
84
89
  }
90
+
85
91
  leases.add(lease);
86
92
  this.#activeConsultations += 1;
93
+
87
94
  if (this.#activeConsultations === 1) {
88
95
  this.safeReport(false);
89
96
  }
97
+
90
98
  return () => this.finishLease(owner, lease);
91
99
  }
92
100
 
93
101
  private finishFor(owner: symbol) {
94
102
  const lease = this.#activeByOwner.get(owner)?.values().next().value;
103
+
95
104
  if (lease) {
96
105
  this.finishLease(owner, lease);
97
106
  }
@@ -99,13 +108,17 @@ export class HerdrAdvisorActivity implements HerdrAdvisorActivityScope {
99
108
 
100
109
  private finishLease(owner: symbol, lease: symbol) {
101
110
  const leases = this.#activeByOwner.get(owner);
111
+
102
112
  if (!leases?.delete(lease)) {
103
113
  return;
104
114
  }
115
+
105
116
  if (leases.size === 0) {
106
117
  this.#activeByOwner.delete(owner);
107
118
  }
119
+
108
120
  this.#activeConsultations -= 1;
121
+
109
122
  if (this.#activeConsultations === 0) {
110
123
  this.safeReport(true);
111
124
  }
@@ -113,11 +126,14 @@ export class HerdrAdvisorActivity implements HerdrAdvisorActivityScope {
113
126
 
114
127
  private clearFor(owner: symbol) {
115
128
  const leases = this.#activeByOwner.get(owner);
129
+
116
130
  if (!leases?.size) {
117
131
  return;
118
132
  }
133
+
119
134
  this.#activeByOwner.delete(owner);
120
135
  this.#activeConsultations -= leases.size;
136
+
121
137
  if (this.#activeConsultations === 0) {
122
138
  this.safeReport(true);
123
139
  }
@@ -136,6 +152,7 @@ export const notifyHerdrAdvisorFailure = (title: string, body: string) => {
136
152
  if (!getAdvisorSettings().herdrIntegration) {
137
153
  return;
138
154
  }
155
+
139
156
  try {
140
157
  sendToHerdr(createHerdrNotificationRequest(title, body));
141
158
  } catch {
@@ -147,6 +164,7 @@ export const herdrAdvisorActivity = new HerdrAdvisorActivity(
147
164
  sendToHerdr,
148
165
  () => getAdvisorSettings().herdrIntegration
149
166
  );
167
+
150
168
  export const herdrAdvisorBlock = new HerdrAdvisorBlock(
151
169
  sendToHerdr,
152
170
  () => getAdvisorSettings().herdrIntegration
@@ -28,23 +28,32 @@ const readImageAttachment = async (
28
28
  remaining: number
29
29
  ): Promise<ImageAttachment | undefined> => {
30
30
  const absolute = resolve(root, name);
31
+
31
32
  if (!within(root, absolute)) {
32
33
  return;
33
34
  }
35
+
34
36
  const stats = await lstat(absolute);
37
+
35
38
  if (stats.isSymbolicLink() || !stats.isFile()) {
36
39
  return;
37
40
  }
41
+
38
42
  const resolved = await realpath(absolute);
43
+
39
44
  if (!within(root, resolved)) {
40
45
  return;
41
46
  }
47
+
42
48
  const flags = constants.O_NOFOLLOW
43
49
  ? constants.O_RDONLY + constants.O_NOFOLLOW
44
50
  : constants.O_RDONLY;
51
+
45
52
  const file = await open(resolved, flags);
53
+
46
54
  try {
47
55
  const opened = await file.stat();
56
+
48
57
  if (
49
58
  !opened.isFile() ||
50
59
  opened.size > ADVISOR_IMAGE_MAX_BYTES ||
@@ -52,12 +61,16 @@ const readImageAttachment = async (
52
61
  ) {
53
62
  return;
54
63
  }
64
+
55
65
  const buffer = Buffer.alloc(opened.size + 1);
56
66
  const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
67
+
57
68
  if (bytesRead !== opened.size) {
58
69
  return;
59
70
  }
71
+
60
72
  const image = imageFromBytes(buffer.subarray(0, bytesRead), mimeType);
73
+
61
74
  return image ? { bytes: bytesRead, image, path: name } : undefined;
62
75
  } finally {
63
76
  await file.close();
@@ -79,27 +92,36 @@ export const readImageFiles = async (
79
92
  : []
80
93
  ),
81
94
  ];
95
+
82
96
  if (!enabled || !names.length) {
83
97
  return { images: [], omitted: names.length };
84
98
  }
99
+
85
100
  const root = await repositoryRoot(cwd);
101
+
86
102
  if (!root) {
87
103
  return { images: [], omitted: names.length };
88
104
  }
105
+
89
106
  const seen = new Set<string>();
90
107
  const images: ImageAttachment[] = [];
91
108
  let omitted = 0;
92
109
  let bytes = 0;
110
+
93
111
  for (const path of names) {
94
112
  const name = normalizeRequestedPath(root, path);
113
+
95
114
  if (name && seen.has(name)) {
96
115
  continue;
97
116
  }
117
+
98
118
  if (name) {
99
119
  seen.add(name);
100
120
  }
121
+
101
122
  try {
102
123
  const mime = name && imageMime(name);
124
+
103
125
  const image =
104
126
  name &&
105
127
  mime &&
@@ -108,6 +130,7 @@ export const readImageFiles = async (
108
130
  isPermitted(root, name, kind)
109
131
  ? await readImageAttachment(root, name, mime, remainingBytes - bytes)
110
132
  : undefined;
133
+
111
134
  if (image) {
112
135
  images.push(image);
113
136
  bytes += image.bytes;
@@ -118,5 +141,6 @@ export const readImageFiles = async (
118
141
  omitted += 1;
119
142
  }
120
143
  }
144
+
121
145
  return { images, omitted };
122
146
  };
@@ -6,17 +6,22 @@ const isPng = (bytes: Buffer): boolean => {
6
6
  if (bytes.length < 57 || !bytes.subarray(0, 8).equals(PNG_SIGNATURE)) {
7
7
  return false;
8
8
  }
9
+
9
10
  let offset = 8;
10
11
  let hasHeader = false;
11
12
  const compressed: Buffer[] = [];
13
+
12
14
  while (offset + 12 <= bytes.length) {
13
15
  const length = bytes.readUInt32BE(offset);
16
+
14
17
  if (length > bytes.length - offset - 12) {
15
18
  return false;
16
19
  }
20
+
17
21
  const type = bytes.toString("ascii", offset + 4, offset + 8);
18
22
  const data = offset + 8;
19
23
  offset += length + 12;
24
+
20
25
  if (!hasHeader) {
21
26
  if (
22
27
  type !== "IHDR" ||
@@ -26,6 +31,7 @@ const isPng = (bytes: Buffer): boolean => {
26
31
  ) {
27
32
  return false;
28
33
  }
34
+
29
35
  hasHeader = true;
30
36
  } else if (type === "IDAT") {
31
37
  compressed.push(bytes.subarray(data, data + length));
@@ -33,6 +39,7 @@ const isPng = (bytes: Buffer): boolean => {
33
39
  if (length !== 0 || offset !== bytes.length || !compressed.length) {
34
40
  return false;
35
41
  }
42
+
36
43
  try {
37
44
  return (
38
45
  inflateSync(Buffer.concat(compressed), {
@@ -46,6 +53,7 @@ const isPng = (bytes: Buffer): boolean => {
46
53
  return false;
47
54
  }
48
55
  }
56
+
49
57
  return false;
50
58
  };
51
59
 
@@ -57,20 +65,26 @@ const isFrameMarker = (marker: number) =>
57
65
 
58
66
  const nextScanMarker = (bytes: Buffer, from: number): number => {
59
67
  let offset = from;
68
+
60
69
  while (offset < bytes.length - 1) {
61
70
  if (bytes[offset] !== 0xff) {
62
71
  offset += 1;
63
72
  continue;
64
73
  }
74
+
65
75
  let next = offset + 1;
76
+
66
77
  while (bytes[next] === 0xff) {
67
78
  next += 1;
68
79
  }
80
+
69
81
  if (bytes[next] !== 0x00 && (bytes[next] < 0xd0 || bytes[next] > 0xd7)) {
70
82
  return offset;
71
83
  }
84
+
72
85
  offset = next + 1;
73
86
  }
87
+
74
88
  return bytes.length;
75
89
  };
76
90
 
@@ -88,27 +102,36 @@ const readJpegSegment = (
88
102
  if (bytes[at] !== 0xff) {
89
103
  return;
90
104
  }
105
+
91
106
  let offset = at;
107
+
92
108
  while (bytes[offset] === 0xff) {
93
109
  offset += 1;
94
110
  }
111
+
95
112
  const marker = bytes[offset];
96
113
  offset += 1;
114
+
97
115
  if (marker === 0xd9) {
98
116
  return { end: offset, frame: false, marker, size: 0 };
99
117
  }
118
+
100
119
  if (offset + 2 > bytes.length || marker === 0x00) {
101
120
  return;
102
121
  }
122
+
103
123
  const size = bytes.readUInt16BE(offset);
124
+
104
125
  if (size < 2 || offset + size > bytes.length) {
105
126
  return;
106
127
  }
128
+
107
129
  const frame =
108
130
  isFrameMarker(marker) &&
109
131
  size >= 11 &&
110
132
  bytes.readUInt16BE(offset + 3) > 0 &&
111
133
  bytes.readUInt16BE(offset + 5) > 0;
134
+
112
135
  return { end: offset + size, frame, marker, size };
113
136
  };
114
137
 
@@ -123,50 +146,65 @@ const isJpeg = (bytes: Buffer): boolean => {
123
146
  if (!hasJpegEnvelope(bytes)) {
124
147
  return false;
125
148
  }
149
+
126
150
  let offset = 2;
127
151
  let frame = false;
128
152
  let scan = false;
129
153
  let quantization = false;
130
154
  let entropyTable = false;
155
+
131
156
  while (offset < bytes.length) {
132
157
  const segment = readJpegSegment(bytes, offset);
158
+
133
159
  if (!segment) {
134
160
  return false;
135
161
  }
162
+
136
163
  const { end, marker, size } = segment;
164
+
137
165
  if (marker === 0xd9) {
138
166
  return frame && scan && end === bytes.length;
139
167
  }
168
+
140
169
  frame ||= segment.frame;
141
170
  quantization ||= marker === 0xdb;
142
171
  entropyTable ||= marker === 0xc4 || marker === 0xcc;
143
172
  offset = end;
173
+
144
174
  if (marker === 0xda) {
145
175
  if (!(frame && quantization && entropyTable && size >= 6)) {
146
176
  return false;
147
177
  }
178
+
148
179
  const next = nextScanMarker(bytes, offset);
180
+
149
181
  if (next <= offset) {
150
182
  return false;
151
183
  }
184
+
152
185
  scan = true;
153
186
  offset = next;
154
187
  }
155
188
  }
189
+
156
190
  return false;
157
191
  };
158
192
 
159
193
  const skipGifBlocks = (bytes: Buffer, at: number): number | undefined => {
160
194
  let offset = at;
195
+
161
196
  while (offset < bytes.length) {
162
197
  const length = bytes[offset];
163
198
  offset += 1;
199
+
164
200
  if (length === 0) {
165
201
  return offset;
166
202
  }
203
+
167
204
  if (offset + length > bytes.length) {
168
205
  return;
169
206
  }
207
+
170
208
  offset += length;
171
209
  }
172
210
  };
@@ -182,7 +220,9 @@ const gifFrameEnd = (bytes: Buffer, at: number): number | undefined => {
182
220
  ) {
183
221
  return;
184
222
  }
223
+
185
224
  const data = gifColorTableEnd(bytes, at + 9, bytes[at + 8]);
225
+
186
226
  if (
187
227
  data + 2 >= bytes.length ||
188
228
  bytes[data] < 2 ||
@@ -191,6 +231,7 @@ const gifFrameEnd = (bytes: Buffer, at: number): number | undefined => {
191
231
  ) {
192
232
  return;
193
233
  }
234
+
194
235
  return skipGifBlocks(bytes, data + 1);
195
236
  };
196
237
 
@@ -203,27 +244,34 @@ const isGif = (bytes: Buffer): boolean => {
203
244
  ) {
204
245
  return false;
205
246
  }
247
+
206
248
  let offset = gifColorTableEnd(bytes, 13, bytes[10]);
207
249
  let frame = false;
250
+
208
251
  while (offset < bytes.length) {
209
252
  const block = bytes[offset];
210
253
  offset += 1;
254
+
211
255
  if (block === 0x3b) {
212
256
  return frame && offset === bytes.length;
213
257
  }
258
+
214
259
  if (block === 0x21 && offset < bytes.length) {
215
260
  offset = skipGifBlocks(bytes, offset + 1) ?? bytes.length;
216
261
  } else if (block === 0x2c) {
217
262
  const end = gifFrameEnd(bytes, offset);
263
+
218
264
  if (end === undefined) {
219
265
  return false;
220
266
  }
267
+
221
268
  frame = true;
222
269
  offset = end;
223
270
  } else {
224
271
  return false;
225
272
  }
226
273
  }
274
+
227
275
  return false;
228
276
  };
229
277
 
@@ -241,9 +289,11 @@ const validWebpFrame = (
241
289
  (bytes.readUInt16LE(data + 8) & 0x3fff) > 0
242
290
  );
243
291
  }
292
+
244
293
  if (type === "VP8L") {
245
294
  return length >= 5 && bytes[data] === 0x2f;
246
295
  }
296
+
247
297
  return type === "ANMF" && length >= 16;
248
298
  };
249
299
 
@@ -256,19 +306,24 @@ const isWebp = (bytes: Buffer): boolean => {
256
306
  ) {
257
307
  return false;
258
308
  }
309
+
259
310
  let offset = 12;
260
311
  let frame = false;
312
+
261
313
  while (offset + 8 <= bytes.length) {
262
314
  const type = bytes.toString("ascii", offset, offset + 4);
263
315
  const length = bytes.readUInt32LE(offset + 4);
264
316
  const data = offset + 8;
265
317
  const end = data + length + (length % 2);
318
+
266
319
  if (end > bytes.length) {
267
320
  return false;
268
321
  }
322
+
269
323
  frame ||= validWebpFrame(bytes, type, data, length);
270
324
  offset = end;
271
325
  }
326
+
272
327
  return frame && offset === bytes.length;
273
328
  };
274
329
 
@@ -276,12 +331,15 @@ export const detectImageFormat = (bytes: Buffer): string | undefined => {
276
331
  if (isPng(bytes)) {
277
332
  return "image/png";
278
333
  }
334
+
279
335
  if (isJpeg(bytes)) {
280
336
  return "image/jpeg";
281
337
  }
338
+
282
339
  if (isGif(bytes)) {
283
340
  return "image/gif";
284
341
  }
342
+
285
343
  if (isWebp(bytes)) {
286
344
  return "image/webp";
287
345
  }
package/src/images.ts CHANGED
@@ -20,10 +20,13 @@ export const imageFromBytes = (
20
20
  if (!bytes.length || bytes.length > ADVISOR_IMAGE_MAX_BYTES) {
21
21
  return;
22
22
  }
23
+
23
24
  const actual = detectImageFormat(bytes);
25
+
24
26
  if (!actual || (mimeType && mimeType !== actual)) {
25
27
  return;
26
28
  }
29
+
27
30
  return { data: bytes.toString("base64"), mimeType: actual, type: "image" };
28
31
  };
29
32
 
@@ -39,10 +42,13 @@ export const imageFromPart = (part: RecordValue): ImageContent | undefined => {
39
42
  ) {
40
43
  return;
41
44
  }
45
+
42
46
  const bytes = Buffer.from(part.data, "base64");
47
+
43
48
  if (bytes.toString("base64") !== part.data) {
44
49
  return;
45
50
  }
51
+
46
52
  return imageFromBytes(bytes, part.mimeType);
47
53
  };
48
54
 
@@ -53,15 +59,19 @@ export const imageMarker = (
53
59
  if (part.type !== "image") {
54
60
  return;
55
61
  }
62
+
56
63
  const image = imageFromPart(part);
64
+
57
65
  if (!image) {
58
66
  return "[Image omitted: unsupported format, invalid data, or over 4 MiB; pixels not reviewed]";
59
67
  }
68
+
60
69
  const id = createHash("sha256")
61
70
  .update(nonce)
62
71
  .update(image.data)
63
72
  .digest("hex")
64
73
  .slice(0, 24);
74
+
65
75
  return `[Image ref=img_${id}; pixels reviewed only if attached below]`;
66
76
  };
67
77
 
@@ -91,23 +101,30 @@ const entryImageCensus = (
91
101
  ): ImagePartCensus => {
92
102
  let parts = 0;
93
103
  const selected: SelectedImage[] = [];
104
+
94
105
  for (const part of contentParts(content)) {
95
106
  if (!isRecordOf(part)) {
96
107
  continue;
97
108
  }
109
+
98
110
  if (eligibleImagePart(part)) {
99
111
  parts += 1;
100
112
  }
113
+
101
114
  const marker = imageMarker(part, nonce);
115
+
102
116
  if (!marker || seen.has(marker) || !conversation.includes(marker)) {
103
117
  continue;
104
118
  }
119
+
105
120
  const image = imageFromPart(part);
121
+
106
122
  if (image) {
107
123
  seen.add(marker);
108
124
  selected.push({ image, marker });
109
125
  }
110
126
  }
127
+
111
128
  return { parts, selected };
112
129
  };
113
130
 
@@ -121,10 +138,12 @@ export const selectedConversationImages = (
121
138
  if (!conversation) {
122
139
  return { imagePartsSeen: 0, selected: [] };
123
140
  }
141
+
124
142
  const entries = sessionContextEntries(ctx);
125
143
  const images: SelectedImage[] = [];
126
144
  const seen = new Set<string>();
127
145
  let imagePartsSeen = 0;
146
+
128
147
  for (const [index, entry] of entries.entries()) {
129
148
  if (
130
149
  entry.type !== "message" ||
@@ -133,19 +152,24 @@ export const selectedConversationImages = (
133
152
  ) {
134
153
  continue;
135
154
  }
155
+
136
156
  const { message } = entry;
157
+
137
158
  if (message.role !== "user" && message.role !== "toolResult") {
138
159
  continue;
139
160
  }
161
+
140
162
  if (
141
163
  message.role === "toolResult" &&
142
164
  (policies[message.toolName] ?? "full") !== "full"
143
165
  ) {
144
166
  continue;
145
167
  }
168
+
146
169
  const census = entryImageCensus(message.content, conversation, nonce, seen);
147
170
  imagePartsSeen += census.parts;
148
171
  images.push(...census.selected);
149
172
  }
173
+
150
174
  return { imagePartsSeen, selected: images };
151
175
  };