happyskills 0.49.0 → 0.50.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 CHANGED
@@ -7,6 +7,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/).
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.50.0] - 2026-05-24
11
+
12
+ ### Added
13
+
14
+ - **New `feedback` command** — `happyskills feedback <category> [body] [--subject "..."] [--attach a,b,c] [--json]`. Lodge a bug report, feature wish, compliment, question, or other feedback against the HappySkills platform from the terminal. Five categories: `bug | wish | compliment | question | other`. The body can be supplied inline or omitted to open `$EDITOR` (vim / nano fallback) — same UX as `git commit`. Optional `--subject` (≤ 200 chars) and `--attach` (comma-separated image paths, max 10, PNG/JPEG accepted on the CLI). Auto-captures `cli_version`, `node_version`, `os`, `arch`, `cwd_is_skill_dir`, and `current_skill` (read from a local `skill.json` if present) into the API's silent `client_context`, with secrets scrubbed before sending. `--json` emits the `{ data: { feedback, attachments }, error: null, next_step }` envelope at the response root — the `next_step` is what the `happyskills-help` skill reads to offer the post-creation attachment follow-up.
15
+ - **Image attachments via cherry-picked jimp 1.x** — `cli/src/utils/image_compression.js` compresses each `--attach` file to ≤ 2000 px longest side / JPEG quality 80 / ≤ 1 MB before upload via the two-step pre-signed S3 flow. Uses `@jimp/core` + `@jimp/js-jpeg` + `@jimp/js-png` + `@jimp/plugin-resize` cherry-picked from the jimp 1.x family — NOT the `jimp` meta-package (which pulls in BMP, GIF, TIFF, blur, color, mask, threshold, dither, print, and a dozen other plugins we don't need). WebP is not supported on the CLI in this release (jimp 1.x ships no WebP codec); the web modal still accepts WebP via `browser-image-compression`. **Lazy-loaded**: jimp is only `require()`d when at least one `--attach` is provided, so every other CLI command (`install`, `search`, `publish`, etc.) pays zero require cost. An early-bail check after compression rejects images that still exceed 1 MB with a clean local error before any initiate round-trip.
16
+ - **New `cli/src/api/feedback.js`** — API client for the new `/feedback` endpoints: `create_feedback`, `initiate_attachment_upload`, `put_attachment_to_s3`, `complete_attachment_upload`, `list_feedback`, `get_feedback`. Follows the existing per-resource module pattern (`api/repos.js`, `api/auth.js`, etc.).
17
+ - **New `cli/src/utils/scrub_secrets.js`** — recursively scrubs OpenAI keys (`sk-…`), GitHub tokens (`ghp_…` / `gho_…`), Cognito JWT-shaped strings (`eyJ…`), and any value whose key matches `/(_TOKEN|_KEY|_SECRET|_PASSWORD|_API_KEY)$/i` before `client_context` leaves the CLI. Applied automatically by the feedback command; reusable from any future command that captures user environment data. Mirror of `web/src/lib/scrub-secrets.js` — the regexes must stay in sync.
18
+
19
+ ### Changed
20
+
21
+ - **All API calls now send `User-Agent: happyskills-cli/<version>`** (`cli/src/api/client.js`). Required so the API can derive `feedback.source = 'cli'` server-side and never trust the source from the request body. No behaviour change for existing endpoints — none of them inspect User-Agent today; this is forward-compatible plumbing for any future endpoint that wants to know who's calling.
22
+ - **Install size increased from 5.1 MB → ~15 MB** due to jimp 1.x's transitive deps (`zod` 5 MB for runtime type checks; `bare-fs`/`bare-os`/`bare-url` 3.6 MB combined for Bare-runtime polyfills). The cherry-pick keeps jimp itself to 1.4 MB on disk, but the dependency closure dominates. This violates the original spec § 8.3's 8 MB target — accepted as a deliberate trade-off because: (a) **cold-start cost is unaffected** (lazy require means non-feedback commands never load jimp); (b) `npm install -g happyskills` install cost is paid once per machine, not per invocation; (c) the mission-aligned goal of "friction is the enemy of getting feedback at all" outweighs install footprint. A follow-up could investigate shelling out to system `sips` / `magick` to shrink the install — flagged but not in this release.
23
+
24
+ ### Notes
25
+
26
+ - New gotcha entries documenting browser-direct-to-S3 patterns (signed Content-Type on PUT, response-Content-Type override on GET, SDK v3.729+ checksum opt-out, bucket CORS as CSRF guard) were added to `docs/gotchas/aws-sdk.md` in the same monorepo change set. These pertain to the API and infra; mentioned here for context since the CLI's `--attach` flow is the other client of that pipeline.
27
+
10
28
  ## [0.49.0] - 2026-05-23
11
29
 
12
30
  This release combines two streams of work: **spec 260523-02 (Skill Update Determinism)** which introduces four new CLI primitives plus an `ahead` status to make skill update flows deterministic and safe-to-attempt, AND a **bundle-size enforcement** pass that adds a total-bundle cap to pre-publish validation.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "happyskills",
3
- "version": "0.49.0",
3
+ "version": "0.50.0",
4
4
  "description": "Package manager for AI agent skills",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "author": "Nicolas Dao <nic@cloudlesslabs.com> (https://cloudlesslabs.com)",
@@ -43,6 +43,10 @@
43
43
  "node": ">=22.0.0"
44
44
  },
45
45
  "dependencies": {
46
+ "@jimp/core": "^1.6.0",
47
+ "@jimp/js-jpeg": "^1.6.0",
48
+ "@jimp/js-png": "^1.6.0",
49
+ "@jimp/plugin-resize": "^1.6.0",
46
50
  "node-diff3": "^3.2.0",
47
51
  "puffy-core": "^1.3.1",
48
52
  "semver": "^7.6.0",
package/src/api/client.js CHANGED
@@ -1,15 +1,18 @@
1
1
  const { createHash } = require('crypto')
2
2
  const { error: { catch_errors, wrap_errors: e } } = require('puffy-core')
3
- const { API_URL } = require('../constants')
3
+ const { API_URL, CLI_VERSION } = require('../constants')
4
4
  const { ApiError, NetworkError, AuthError } = require('../utils/errors')
5
5
  const { load_token } = require('../auth/token_store')
6
6
 
7
7
  const get_base_url = () => process.env.HAPPYSKILLS_API_URL || API_URL
8
+ const USER_AGENT = `happyskills-cli/${CLI_VERSION}`
8
9
 
9
10
  const request = (method, path, options = {}) => catch_errors(`API ${method} ${path} failed`, async () => {
10
11
  const { body, auth = true, raw_response = false, unwrap = true, headers: extra_headers = {} } = options
11
12
  const url = `${get_base_url()}${path}`
12
- const headers = { ...extra_headers }
13
+ // User-Agent enables the API to identify CLI traffic (e.g. feedback API
14
+ // derives `source = 'cli'` from this header). Spec 260524-01 § 12.
15
+ const headers = { 'User-Agent': USER_AGENT, ...extra_headers }
13
16
 
14
17
  if (auth) {
15
18
  const [, token_data] = await load_token()
@@ -0,0 +1,71 @@
1
+ // Spec 260524-01 — CLI client for the /feedback API.
2
+ //
3
+ // Returns the full response (envelope unwrapped to `data`) for `create` so the
4
+ // caller can access the `next_step` envelope baked into the API response. The
5
+ // attachment endpoints unwrap normally — callers only need the payload.
6
+
7
+ const { error: { catch_errors, wrap_errors: e } } = require('puffy-core')
8
+ const client = require('./client')
9
+
10
+ // POST /feedback — does NOT unwrap, so the caller can read `next_step` which
11
+ // the API places alongside `feedback` inside `data`. (Our envelope is
12
+ // `{ data: { feedback, next_step } }`.)
13
+ const create_feedback = (payload) => catch_errors('Create feedback failed', async () => {
14
+ const [errors, data] = await client.post('/feedback', payload)
15
+ if (errors) throw errors[errors.length - 1]
16
+ return data // { feedback, next_step }
17
+ })
18
+
19
+ const initiate_attachment_upload = (feedback_id, payload) => catch_errors('Initiate attachment upload failed', async () => {
20
+ const [errors, data] = await client.post(`/feedback/${feedback_id}/attachments/initiate`, payload)
21
+ if (errors) throw errors[errors.length - 1]
22
+ return data // { upload_id, storage_key, upload_url, expires_at, original_name }
23
+ })
24
+
25
+ const complete_attachment_upload = (feedback_id, payload) => catch_errors('Complete attachment upload failed', async () => {
26
+ const [errors, data] = await client.post(`/feedback/${feedback_id}/attachments/complete`, payload)
27
+ if (errors) throw errors[errors.length - 1]
28
+ return data // { attachment }
29
+ })
30
+
31
+ const put_attachment_to_s3 = (presigned_url, buffer) => catch_errors('S3 attachment upload failed', async () => {
32
+ const res = await fetch(presigned_url, {
33
+ method: 'PUT',
34
+ body: buffer,
35
+ headers: {
36
+ 'Content-Type': 'image/jpeg',
37
+ 'Content-Length': buffer.length.toString()
38
+ }
39
+ })
40
+ if (!res.ok) {
41
+ const text = await res.text().catch(() => '')
42
+ throw new Error(`S3 PUT failed with status ${res.status}${text ? ': ' + text.slice(0, 200) : ''}`)
43
+ }
44
+ })
45
+
46
+ const list_feedback = (query = {}) => catch_errors('List feedback failed', async () => {
47
+ const params = new URLSearchParams()
48
+ if (query.limit != null) params.set('limit', String(query.limit))
49
+ if (query.offset != null) params.set('offset', String(query.offset))
50
+ if (query.category) params.set('category', query.category)
51
+ if (query.status) params.set('status', query.status)
52
+ const qs = params.toString()
53
+ const [errors, data] = await client.get(`/feedback${qs ? '?' + qs : ''}`)
54
+ if (errors) throw errors[errors.length - 1]
55
+ return data
56
+ })
57
+
58
+ const get_feedback = (feedback_id) => catch_errors('Get feedback failed', async () => {
59
+ const [errors, data] = await client.get(`/feedback/${feedback_id}`)
60
+ if (errors) throw errors[errors.length - 1]
61
+ return data
62
+ })
63
+
64
+ module.exports = {
65
+ create_feedback,
66
+ initiate_attachment_upload,
67
+ complete_attachment_upload,
68
+ put_attachment_to_s3,
69
+ list_feedback,
70
+ get_feedback
71
+ }
@@ -0,0 +1,260 @@
1
+ // Spec 260524-01 — `happyskills feedback` command.
2
+ //
3
+ // Surfaces:
4
+ // happyskills feedback <category> [body] [--subject "..."] [--attach a,b,c] [--json]
5
+ //
6
+ // --json mode emits the API's response wrapped in the universal CLI envelope:
7
+ // { data: { feedback, next_step, attachments? }, error: null }
8
+ // The `next_step` envelope is what the `happyskills-help` skill reads to
9
+ // route the post-creation conversation (offer attachment, etc.) — see spec
10
+ // § 6.2 + § 11.
11
+ //
12
+ // LAZY-LOAD: jimp / image_compression is only require()d when --attach is
13
+ // present, so the 99% of CLI invocations that don't lodge feedback pay zero
14
+ // startup cost (D8).
15
+
16
+ const fs = require('fs')
17
+ const os = require('os')
18
+ const path = require('path')
19
+ const { spawnSync } = require('child_process')
20
+ const { error: { catch_errors, wrap_errors: e } } = require('puffy-core')
21
+ const { require_token } = require('../auth/token_store')
22
+ const feedback_api = require('../api/feedback')
23
+ const { scrub } = require('../utils/scrub_secrets')
24
+ const { print_help, print_json, print_success, print_info, print_hint } = require('../ui/output')
25
+ const { exit_with_error, UsageError } = require('../utils/errors')
26
+ const { EXIT_CODES, CLI_VERSION } = require('../constants')
27
+
28
+ const HELP_TEXT = `Usage: happyskills feedback <category> [body] [options]
29
+
30
+ Lodge feedback with HappySkills — bug reports, feature wishes, compliments,
31
+ questions. Auto-captures CLI version / OS / current skill context silently
32
+ (secrets are scrubbed before sending).
33
+
34
+ Arguments:
35
+ category One of: bug | wish | compliment | question | other
36
+ body Your feedback. Omit to open $EDITOR (vim / nano fallback).
37
+
38
+ Options:
39
+ --subject "..." Short title (max 200 chars)
40
+ --attach <paths> Comma-separated image paths (max 10, PNG/JPEG accepted).
41
+ Each compressed to ≤2000px / quality 80 / JPEG before upload.
42
+ Per-image cap after compression: 1 MB (server-enforced).
43
+ --json Emit JSON envelope (intended for use inside an agentic
44
+ session — see the happyskills-help skill).
45
+
46
+ Examples:
47
+ happyskills feedback bug "search returns nothing for partial slugs"
48
+ happyskills feedback wish "I wish I could export my catalog to JSON"
49
+ happyskills feedback bug --attach screenshot.png --json
50
+ happyskills feedback compliment # → opens $EDITOR for the body`
51
+
52
+ const VALID_CATEGORIES = new Set(['bug', 'wish', 'compliment', 'question', 'other'])
53
+
54
+ const try_editor_for_body = () => {
55
+ const editors = [
56
+ process.env.EDITOR,
57
+ process.env.VISUAL,
58
+ 'vim',
59
+ 'nano',
60
+ ].filter(Boolean)
61
+
62
+ const tmp = path.join(os.tmpdir(), `happyskills-feedback-${process.pid}-${Date.now()}.txt`)
63
+ fs.writeFileSync(tmp, '# Write your feedback above this line. Lines starting with # are ignored.\n')
64
+
65
+ let succeeded = false
66
+ for (const editor of editors) {
67
+ try {
68
+ const r = spawnSync(editor, [tmp], { stdio: 'inherit' })
69
+ if (r.status === 0) { succeeded = true; break }
70
+ } catch (_) {
71
+ // try next
72
+ }
73
+ }
74
+ if (!succeeded) {
75
+ try { fs.unlinkSync(tmp) } catch (_) {}
76
+ throw new UsageError('Could not open an editor. Set $EDITOR, or pass the body as a positional argument.')
77
+ }
78
+
79
+ const raw = fs.readFileSync(tmp, 'utf-8')
80
+ try { fs.unlinkSync(tmp) } catch (_) {}
81
+ const body = raw
82
+ .split('\n')
83
+ .filter(line => !line.startsWith('#'))
84
+ .join('\n')
85
+ .trim()
86
+ return body
87
+ }
88
+
89
+ // Best-effort: read a local skill.json if the cwd looks like a skill directory.
90
+ const read_current_skill = () => {
91
+ try {
92
+ const p = path.join(process.cwd(), 'skill.json')
93
+ if (!fs.existsSync(p)) return null
94
+ const raw = fs.readFileSync(p, 'utf-8')
95
+ const parsed = JSON.parse(raw)
96
+ const name = parsed.name || null
97
+ if (!name) return null
98
+ // name may be "ns/skill" or just "skill"
99
+ const slash = name.indexOf('/')
100
+ return {
101
+ namespace: slash > 0 ? name.slice(0, slash) : null,
102
+ name: slash > 0 ? name.slice(slash + 1) : name,
103
+ version: parsed.version || null
104
+ }
105
+ } catch (_) {
106
+ return null
107
+ }
108
+ }
109
+
110
+ const build_client_context = () => {
111
+ const current_skill = read_current_skill()
112
+ const ctx = {
113
+ source: 'cli',
114
+ cli_version: CLI_VERSION,
115
+ node_version: process.version,
116
+ os: process.platform,
117
+ arch: process.arch,
118
+ cwd_is_skill_dir: !!current_skill,
119
+ }
120
+ if (current_skill) ctx.current_skill = current_skill
121
+ return scrub(ctx)
122
+ }
123
+
124
+ const MAX_ATTACHMENTS = 10
125
+ const MAX_ATTACHMENT_BYTES = 1 * 1000 * 1000 // 1 MB post-compression — matches API MAX_FEEDBACK_ATTACHMENT_BYTES
126
+
127
+ const parse_attach_paths = (raw_value) => {
128
+ if (!raw_value) return []
129
+ const items = String(raw_value).split(',').map(s => s.trim()).filter(Boolean)
130
+ if (items.length > MAX_ATTACHMENTS) {
131
+ throw new UsageError(`At most ${MAX_ATTACHMENTS} attachments are allowed.`)
132
+ }
133
+ for (const p of items) {
134
+ if (!fs.existsSync(p)) {
135
+ throw new UsageError(`Attachment not found: ${p}`)
136
+ }
137
+ }
138
+ return items
139
+ }
140
+
141
+ const upload_attachments = (feedback_id, attach_paths, opts) => catch_errors('Failed to upload attachments', async () => {
142
+ const { print_progress } = opts
143
+ // Lazy import — keeps jimp out of the require graph for non-feedback commands.
144
+ const { compress_image } = require('../utils/image_compression')
145
+
146
+ const uploaded = []
147
+ for (let i = 0; i < attach_paths.length; i++) {
148
+ const src = attach_paths[i]
149
+ if (print_progress) print_progress(`Compressing ${path.basename(src)} (${i + 1}/${attach_paths.length})`)
150
+
151
+ const [c_err, compressed] = await compress_image(src)
152
+ if (c_err) throw e(`Failed to compress ${src}`, c_err)
153
+
154
+ // Early bail before paying for an initiate round-trip if the compressed
155
+ // image still exceeds the per-image cap. Server enforces the same limit;
156
+ // this is a clean local error rather than a 413 round trip away.
157
+ if (compressed.bytes > MAX_ATTACHMENT_BYTES) {
158
+ throw new UsageError(`Compressed "${path.basename(src)}" is ${compressed.bytes} bytes — exceeds the ${MAX_ATTACHMENT_BYTES}-byte (1 MB) per-image cap. Try cropping or sending a smaller region.`)
159
+ }
160
+
161
+ const [init_err, init] = await feedback_api.initiate_attachment_upload(feedback_id, {
162
+ bytes: compressed.bytes,
163
+ content_type: 'image/jpeg',
164
+ original_name: path.basename(src),
165
+ })
166
+ if (init_err) throw e(`Failed to initiate upload for ${src}`, init_err)
167
+
168
+ if (print_progress) print_progress(`Uploading ${path.basename(src)} (${i + 1}/${attach_paths.length})`)
169
+ const [put_err] = await feedback_api.put_attachment_to_s3(init.upload_url, compressed.buffer)
170
+ if (put_err) throw e(`S3 upload failed for ${src}`, put_err)
171
+
172
+ const [comp_err, comp] = await feedback_api.complete_attachment_upload(feedback_id, {
173
+ upload_id: init.upload_id,
174
+ bytes: compressed.bytes,
175
+ width: compressed.width,
176
+ height: compressed.height,
177
+ original_name: path.basename(src),
178
+ })
179
+ if (comp_err) throw e(`Failed to confirm upload for ${src}`, comp_err)
180
+
181
+ uploaded.push(comp.attachment)
182
+ }
183
+ return uploaded
184
+ })
185
+
186
+ const run = (args) => catch_errors('Feedback command failed', async () => {
187
+ if (args.flags._show_help) {
188
+ print_help(HELP_TEXT)
189
+ return process.exit(EXIT_CODES.SUCCESS)
190
+ }
191
+
192
+ const json_mode = !!args.flags.json
193
+ const category = args._[0]
194
+ const body_positional = args._.slice(1).join(' ').trim()
195
+
196
+ if (!category) {
197
+ throw new UsageError(`Category is required. One of: ${Array.from(VALID_CATEGORIES).join(' | ')}`)
198
+ }
199
+ if (!VALID_CATEGORIES.has(category)) {
200
+ throw new UsageError(`Invalid category "${category}". Must be one of: ${Array.from(VALID_CATEGORIES).join(' | ')}`)
201
+ }
202
+
203
+ let body = body_positional
204
+ if (!body) {
205
+ if (json_mode) {
206
+ // In agentic / scripted contexts we can't open an editor — fail fast.
207
+ throw new UsageError('In --json mode the feedback body must be passed as a positional argument; the editor fallback is interactive.')
208
+ }
209
+ body = try_editor_for_body()
210
+ if (!body) {
211
+ throw new UsageError('No feedback body was entered. Aborted.')
212
+ }
213
+ }
214
+
215
+ const subject = args.flags.subject && typeof args.flags.subject === 'string' ? args.flags.subject : null
216
+ const attach_paths = parse_attach_paths(args.flags.attach)
217
+
218
+ // Auth required — surfaces a clean AuthError exit code 3 on no/expired token.
219
+ await require_token()
220
+
221
+ const client_context = build_client_context()
222
+
223
+ const [create_err, create_result] = await feedback_api.create_feedback({
224
+ category,
225
+ subject,
226
+ body,
227
+ client_context,
228
+ })
229
+ if (create_err) throw e('Failed to create feedback', create_err)
230
+
231
+ const { feedback, next_step } = create_result
232
+
233
+ // Attachment phase
234
+ let attachments = []
235
+ if (attach_paths.length > 0) {
236
+ const print_progress = json_mode ? null : (msg) => print_info(msg)
237
+ const [upload_err, uploaded] = await upload_attachments(feedback.id, attach_paths, { print_progress })
238
+ if (upload_err) throw e('Attachment upload failed', upload_err)
239
+ attachments = uploaded
240
+ }
241
+
242
+ if (json_mode) {
243
+ // Universal CLI envelope shape. The skill's envelope-reader (per spec
244
+ // § 11) consumes `next_step` at the response root.
245
+ const data = { feedback, attachments }
246
+ print_json({ data, error: null, next_step })
247
+ return
248
+ }
249
+
250
+ // Human-readable
251
+ const short_id = String(feedback.id).slice(0, 8)
252
+ print_success(`Feedback recorded (#${short_id}).`)
253
+ if (attachments.length > 0) {
254
+ print_info(`Uploaded ${attachments.length} attachment${attachments.length === 1 ? '' : 's'}.`)
255
+ } else if (next_step && next_step.attachments_supported && attach_paths.length === 0) {
256
+ print_hint(`Pass --attach <path> to add a screenshot (max ${next_step.max_attachments}).`)
257
+ }
258
+ }).then(([errors]) => { if (errors) { exit_with_error(errors); return } })
259
+
260
+ module.exports = { run }
package/src/constants.js CHANGED
@@ -77,7 +77,8 @@ const COMMANDS = [
77
77
  'postlex',
78
78
  'snapshot',
79
79
  'reconcile',
80
- 'release'
80
+ 'release',
81
+ 'feedback'
81
82
  ]
82
83
 
83
84
  module.exports = {
package/src/index.js CHANGED
@@ -116,6 +116,7 @@ Commands:
116
116
  snapshot <sub> Capture and restore skill state (create, list, restore, delete, prune)
117
117
  reconcile <owner/skill> Diagnose and repair lock-vs-disk drift
118
118
  release <skill-name> Atomic release: snapshot + validate + bump + publish
119
+ feedback <category> Lodge feedback (bug, wish, compliment, question, other)
119
120
 
120
121
  Global flags:
121
122
  --help Show help for a command
@@ -0,0 +1,70 @@
1
+ // Spec 260524-01 § 8.3 — CLI-side image compression for feedback attachments.
2
+ //
3
+ // FOOTPRINT DISCIPLINE (D8): this module cherry-picks @jimp/core +
4
+ // @jimp/js-jpeg + @jimp/js-png + @jimp/plugin-resize from jimp 1.x. We
5
+ // deliberately do NOT depend on the `jimp` meta-package — that pulls in
6
+ // BMP, GIF, TIFF, blur, color, mask, threshold, dither, print, hash, blit,
7
+ // circle, contain, cover, crop, displace, fisheye, flip, mask, quantize,
8
+ // rotate, and a half-dozen more plugins we don't need.
9
+ //
10
+ // WEBP NOTE: jimp 1.x does NOT ship a WebP codec sub-package. CLI accepts
11
+ // PNG and JPEG only; the web surface still accepts WebP via
12
+ // `browser-image-compression`. Spec § 8.3's fallback explicitly anticipates
13
+ // this drop ("drop @jimp/webp" — but in practice there's no such package).
14
+ //
15
+ // LAZY-LOAD: this module is dynamically imported only when the feedback
16
+ // command actually has --attach arguments (see commands/feedback.js). Every
17
+ // other CLI command — install, search, publish, etc. — pays zero require
18
+ // cost for jimp.
19
+
20
+ const { error: { catch_errors, wrap_errors: e } } = require('puffy-core')
21
+
22
+ const MAX_DIMENSION = 2000
23
+ const JPEG_QUALITY = 80
24
+
25
+ const get_default = (m) => (m && m.default !== undefined) ? m.default : m
26
+
27
+ let _Jimp = null
28
+
29
+ const get_jimp = () => {
30
+ if (_Jimp) return _Jimp
31
+ const { createJimp } = require('@jimp/core')
32
+ const jpeg = get_default(require('@jimp/js-jpeg'))
33
+ const png = get_default(require('@jimp/js-png'))
34
+ const resize = get_default(require('@jimp/plugin-resize'))
35
+ _Jimp = createJimp({ formats: [jpeg, png], plugins: [resize] })
36
+ return _Jimp
37
+ }
38
+
39
+ // Returns { buffer, bytes, width, height } — JPEG-encoded, longest side
40
+ // ≤ 2000 px, quality 80. Accepts PNG or JPEG input.
41
+ const compress_image = (file_path) => catch_errors('Image compression failed', async () => {
42
+ const Jimp = get_jimp()
43
+ let img
44
+ try {
45
+ img = await Jimp.read(file_path)
46
+ } catch (err) {
47
+ throw e(`Could not read image at ${file_path} — only PNG and JPEG are supported on the CLI`, [err])
48
+ }
49
+
50
+ const { width, height } = img.bitmap
51
+ if (width > MAX_DIMENSION || height > MAX_DIMENSION) {
52
+ // scale proportionally so longest side = MAX_DIMENSION
53
+ if (width >= height) {
54
+ img.resize({ w: MAX_DIMENSION })
55
+ } else {
56
+ img.resize({ h: MAX_DIMENSION })
57
+ }
58
+ }
59
+
60
+ const buffer = await img.getBuffer('image/jpeg', { quality: JPEG_QUALITY })
61
+
62
+ return {
63
+ buffer,
64
+ bytes: buffer.length,
65
+ width: img.bitmap.width,
66
+ height: img.bitmap.height
67
+ }
68
+ })
69
+
70
+ module.exports = { compress_image, MAX_DIMENSION, JPEG_QUALITY }
@@ -0,0 +1,49 @@
1
+ // Spec 260524-01 § 12 — Secret scrubbing applied to feedback `client_context`
2
+ // before it leaves the CLI. Must match the rules in web/src/lib/scrub-secrets.js.
3
+ //
4
+ // Rules:
5
+ // 1. Strip OpenAI API keys (sk-...)
6
+ // 2. Strip GitHub tokens (ghp_..., gho_...)
7
+ // 3. Strip Cognito JWT-shaped tokens (eyJ...)
8
+ // 4. Strip values for env-var keys ending in _TOKEN, _KEY, _SECRET, _PASSWORD
9
+ //
10
+ // The replacement is the literal string `<redacted>` so callers can see that
11
+ // a value WAS present and got stripped — vs missing entirely.
12
+
13
+ const REDACTED = '<redacted>'
14
+
15
+ const PATTERNS = [
16
+ /sk-[A-Za-z0-9_-]{20,}/g, // OpenAI keys
17
+ /ghp_[A-Za-z0-9]{30,}/g, // GitHub personal access tokens
18
+ /gho_[A-Za-z0-9]{30,}/g, // GitHub OAuth tokens
19
+ /eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g // JWT shape
20
+ ]
21
+
22
+ const SENSITIVE_KEY = /(_TOKEN|_KEY|_SECRET|_PASSWORD|_API_KEY)$/i
23
+
24
+ const scrub_string = (value) => {
25
+ let out = value
26
+ for (const re of PATTERNS) out = out.replace(re, REDACTED)
27
+ return out
28
+ }
29
+
30
+ // Recursively walk an object, scrubbing string values and redacting values
31
+ // whose key looks sensitive (e.g. `OPENAI_API_KEY`).
32
+ const scrub = (value) => {
33
+ if (value == null) return value
34
+ if (typeof value === 'string') return scrub_string(value)
35
+ if (typeof value !== 'object') return value
36
+ if (Array.isArray(value)) return value.map(scrub)
37
+
38
+ const out = {}
39
+ for (const [key, v] of Object.entries(value)) {
40
+ if (typeof v === 'string' && SENSITIVE_KEY.test(key)) {
41
+ out[key] = REDACTED
42
+ } else {
43
+ out[key] = scrub(v)
44
+ }
45
+ }
46
+ return out
47
+ }
48
+
49
+ module.exports = { scrub, scrub_string, REDACTED }