cortico-world-agent-speed 0.2.4 → 0.2.6

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cortico-world-agent-speed",
3
- "version": "0.2.4",
3
+ "version": "0.2.6",
4
4
  "type": "module",
5
5
  "description": "The Coopanion desktop pet with local Agent Speed activity animation",
6
6
  "main": "./src/index.ts",
@@ -0,0 +1,311 @@
1
+ import { constants } from 'node:fs';
2
+ import { open, realpath, stat } from 'node:fs/promises';
3
+ import { extname, isAbsolute, relative, sep } from 'node:path';
4
+ import { COO, nameIn, packFile, type FigureAxis, type FigurePack } from './packs.ts';
5
+ import { filesFromZip, type PackImporter } from './pack-import.ts';
6
+ import type { PetText } from './i18n/index.ts';
7
+
8
+ const PACK_ID = /^[a-z0-9][a-z0-9-]{0,31}$/;
9
+ const LOOK_ID = /^[a-zA-Z0-9_-]{1,128}$/;
10
+ const DEVICE_NAME = /^(?:con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³])(?:\.|$)/i;
11
+ const ZIP_MAX = 32 * 1024 * 1024;
12
+ const ZIP_EXPANDED_MAX = 256 * 1024 * 1024;
13
+ const ZIP_ENTRIES_MAX = 4096;
14
+ const ZIP_PACKS_MAX = 64;
15
+ const MANIFEST_MAX = 1024 * 1024;
16
+ const THUMB_MAX = 256 * 1024;
17
+ const THUMB_TOTAL_MAX = 512 * 1024;
18
+ const LABEL_MAX = 256;
19
+ const CATALOG_MAX = 512 * 1024;
20
+
21
+ export function dressObject(value: unknown): Record<string, unknown> {
22
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('Expected a dressing options object');
23
+ return value as Record<string, unknown>;
24
+ }
25
+
26
+ export function dressKeys(raw: Record<string, unknown>, keys: readonly string[]): void {
27
+ if (Object.keys(raw).some((key) => !keys.includes(key))) throw new Error('Unknown dressing option');
28
+ }
29
+
30
+ export function dressLookId(id: unknown): string {
31
+ if (typeof id !== 'string' || !LOOK_ID.test(id)) throw new Error('Invalid saved look ID');
32
+ return id;
33
+ }
34
+
35
+ export function dressPack(packs: readonly FigurePack[], id: unknown): FigurePack {
36
+ const pack = typeof id === 'string' && PACK_ID.test(id) ? packs.find((p) => p.id === id) : undefined;
37
+ if (!pack) throw new Error('Unknown figure pack');
38
+ return pack;
39
+ }
40
+
41
+ /** As the pet page reads the skin: unknown stored picks stand in for that axis's first option. */
42
+ export function dressPicks(pack: FigurePack, skin: { scheme?: string } & object): Record<string, string> {
43
+ const { axes, presets } = pack.manifest;
44
+ const preset = presets.find((p) => p.id === skin.scheme);
45
+ const parts = skin.scheme?.split('-');
46
+ const fields = skin as Record<string, unknown>;
47
+ return Object.fromEntries(axes.map((axis, i) => {
48
+ const want = pack.id === COO ? fields[axis.id] : preset?.pick[axis.id] ?? parts?.[i];
49
+ return [axis.id, axis.options.find((o) => o.id === want)?.id ?? axis.options[0]!.id];
50
+ }));
51
+ }
52
+
53
+ export function dressScheme(pack: FigurePack, picks: Record<string, string>): string {
54
+ const { axes, presets } = pack.manifest;
55
+ const preset = presets.find((p) => axes.every((a) => p.pick[a.id] === picks[a.id]));
56
+ if (preset) return preset.id;
57
+ const scheme = axes.map((a) => picks[a.id]).join('-');
58
+ if (presets.some((p) => p.id === scheme)) throw new Error('Selected options conflict with a preset ID');
59
+ return scheme;
60
+ }
61
+
62
+ export function checkDressPicks(axes: readonly FigureAxis[], picks: Record<string, unknown>): asserts picks is Record<string, string> {
63
+ for (const [axis, id] of Object.entries(picks)) {
64
+ if (!axes.find((a) => a.id === axis)?.options.some((o) => o.id === id)) throw new Error('Unknown dressing axis or option');
65
+ }
66
+ }
67
+
68
+ const IMAGE_TYPES = {
69
+ '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp',
70
+ } as const;
71
+
72
+ function imageMatches(type: string, bytes: Buffer): boolean {
73
+ if (type === 'image/png') return bytes.length >= 8 && bytes.readUInt32BE(0) === 0x89504e47 && bytes.readUInt32BE(4) === 0x0d0a1a0a;
74
+ if (type === 'image/jpeg') return bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff;
75
+ return bytes.length >= 12 && bytes.toString('ascii', 0, 4) === 'RIFF' && bytes.toString('ascii', 8, 12) === 'WEBP';
76
+ }
77
+
78
+ /** Only manifest-declared raster files. `packFile` checks lexical containment; real paths check symlinks. */
79
+ async function dressThumb(pack: FigurePack, file: string | undefined, limit: number): Promise<{ url: string; bytes: number } | null> {
80
+ if (!file || limit <= 0 || file.includes(':') || file.split(/[\\/]/).some((p) => DEVICE_NAME.test(p))) return null;
81
+ const ext = extname(file).toLowerCase();
82
+ if (!Object.hasOwn(IMAGE_TYPES, ext)) return null;
83
+ const type = IMAGE_TYPES[ext as keyof typeof IMAGE_TYPES];
84
+ const path = packFile(pack, file);
85
+ if (!path) return null;
86
+ try {
87
+ const [root, full] = await Promise.all([realpath(pack.dir), realpath(path)]);
88
+ const rel = relative(root, full);
89
+ if (!rel || rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel) || !(await stat(full)).isFile()) return null;
90
+ const handle = await open(full, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
91
+ try {
92
+ const info = await handle.stat();
93
+ const { size } = info;
94
+ if (!info.isFile() || !size || size > limit) return null;
95
+ const buffer = Buffer.allocUnsafe(size + 1);
96
+ let read = 0;
97
+ while (read < buffer.length) {
98
+ const { bytesRead } = await handle.read(buffer, read, buffer.length - read, read);
99
+ if (!bytesRead) break;
100
+ read += bytesRead;
101
+ }
102
+ if (read !== size) return null;
103
+ const bytes = buffer.subarray(0, read);
104
+ return imageMatches(type, bytes) ? { url: `data:${type};base64,${bytes.toString('base64')}`, bytes: size } : null;
105
+ } finally {
106
+ await handle.close();
107
+ }
108
+ } catch {
109
+ return null;
110
+ }
111
+ }
112
+
113
+ export interface DressPackCard {
114
+ id: string;
115
+ name: string;
116
+ thumb: string | null;
117
+ axes: Array<{ id: string; label: string; options: Array<{ id: string; label: string; thumb?: string | null }> }>;
118
+ picks: Record<string, string>;
119
+ }
120
+
121
+ /** No pack paths, scripts, models or other assets cross this RPC. Bound metadata and inline images separately. */
122
+ export async function dressCatalog(packs: FigurePack[], skin: { figure?: string; scheme?: string } & object, language: string): Promise<DressPackCard[]> {
123
+ let metadata = CATALOG_MAX;
124
+ const label = (text: string) => text.slice(0, LABEL_MAX);
125
+ const spend = (...fields: string[]) => {
126
+ // Reserve room for JSON delimiters, field names, and escapes in labels.
127
+ metadata -= 64 + fields.reduce((n, s) => n + s.length * 6, 0);
128
+ if (metadata < 0) throw new Error('Dressing catalog is too large');
129
+ };
130
+ const cards = packs.map((p): DressPackCard => {
131
+ const name = label(nameIn(p.manifest.name, language));
132
+ spend(p.id, name);
133
+ const axes = p.manifest.axes.map((a) => {
134
+ const axisLabel = label(nameIn(a.name, language));
135
+ spend(a.id, axisLabel);
136
+ return { id: a.id, label: axisLabel, options: a.options.map((o) => {
137
+ const optionLabel = label(nameIn(o.name, language));
138
+ spend(o.id, optionLabel);
139
+ return { id: o.id, label: optionLabel };
140
+ }) };
141
+ });
142
+ return { id: p.id, name, axes, thumb: null, picks: dressPicks(p, p.id === COO || p.id === skin.figure ? skin : {}) };
143
+ });
144
+ let remaining = THUMB_TOTAL_MAX;
145
+ const thumb = async (pack: FigurePack, file?: string) => {
146
+ const result = await dressThumb(pack, file, Math.min(THUMB_MAX, remaining));
147
+ if (result) remaining -= result.bytes;
148
+ return result?.url ?? null;
149
+ };
150
+ // Give each figure's main card an image before spending the budget on its options.
151
+ for (const [i, pack] of packs.entries()) {
152
+ if (pack.manifest.thumb) cards[i]!.thumb = await thumb(pack, pack.manifest.thumb);
153
+ }
154
+ for (const [i, pack] of packs.entries()) {
155
+ for (const [j, axis] of pack.manifest.axes.entries()) {
156
+ for (const [k, option] of axis.options.entries()) {
157
+ if (option.thumb) cards[i]!.axes[j]!.options[k]!.thumb = await thumb(pack, option.thumb);
158
+ }
159
+ }
160
+ }
161
+ return cards;
162
+ }
163
+
164
+ /** ZIP entry names stay distinct even on case-insensitive filesystems and Windows filename rules. */
165
+ function zipEntryCheck(): (name: string, bytes: number) => void {
166
+ const paths = new Map<string, string>();
167
+ const entries = new Set<string>();
168
+ return (name, bytes) => {
169
+ if (entries.size >= ZIP_ENTRIES_MAX) throw new Error('ZIP has too many entries');
170
+ const path = name.endsWith('/') ? name.slice(0, -1) : name;
171
+ const parts = path.split('/');
172
+ if (path.length > 768 || parts.length > 32 || parts.some((p) => !p || p.length > 255 || /[\\<>:"|?*\x00-\x1f\x7f]/.test(p) || /[. ]$/.test(p)
173
+ || DEVICE_NAME.test(p) || p === '__proto__')) throw new Error('ZIP has an invalid entry path');
174
+ if (entries.has(path)) throw new Error('ZIP has duplicate entries');
175
+ entries.add(path);
176
+ if (parts.at(-1)?.toLowerCase() === 'figure.json' && bytes > MANIFEST_MAX) throw new Error('Figure manifest is too large');
177
+ let prefix = '';
178
+ for (const part of parts) {
179
+ prefix += `/${part}`;
180
+ const key = prefix.normalize('NFD').toLowerCase();
181
+ const prior = paths.get(key);
182
+ if (prior !== undefined && prior !== prefix) throw new Error('ZIP has ambiguous entry paths');
183
+ paths.set(key, prefix);
184
+ }
185
+ };
186
+ }
187
+
188
+ function zipBytes(raw: unknown): Buffer {
189
+ if (typeof raw !== 'string' || !raw.length || raw.length > Math.ceil(ZIP_MAX / 3) * 4 || raw.length % 4 !== 0) {
190
+ throw new Error('Expected a base64 ZIP of at most 32 MiB');
191
+ }
192
+ // Avoid a repeated capture on a single large upload. Buffer's decoder alone accepts ignored characters.
193
+ const end = raw.endsWith('==') ? raw.length - 2 : raw.endsWith('=') ? raw.length - 1 : raw.length;
194
+ if (/[^A-Za-z0-9+/]/.test(raw.slice(0, end))) throw new Error('Invalid ZIP base64');
195
+ const bytes = Buffer.from(raw, 'base64');
196
+ if (bytes.length < 22 || bytes.length > ZIP_MAX || bytes[0] !== 0x50 || bytes[1] !== 0x4b) throw new Error('Expected a ZIP of at most 32 MiB');
197
+ return bytes;
198
+ }
199
+
200
+ export interface DressImportPreview {
201
+ token: string;
202
+ packs: Array<{ dir: string; id: string; name: string; installed: string | null }>;
203
+ problems: Array<{ dir: string; reason: string }>;
204
+ }
205
+
206
+ /** One stage, scoped to the inline panel. Disk writes are still ordered with the standalone importer. */
207
+ export class DressImport {
208
+ private readonly importer: PackImporter;
209
+ private stage: { token: string; ids: Map<string, string> } | null = null;
210
+ private pending: Promise<unknown> | null = null;
211
+ private uploading: AbortController | null = null;
212
+ private stopped = false;
213
+
214
+ constructor(importer: PackImporter) {
215
+ this.importer = importer.isolated();
216
+ }
217
+
218
+ start(): void { this.stopped = false; }
219
+
220
+ async stop(): Promise<void> {
221
+ this.stopped = true;
222
+ this.uploading?.abort();
223
+ this.stage = null;
224
+ const pending = this.pending;
225
+ try {
226
+ await this.importer.cancel();
227
+ } finally {
228
+ await pending?.catch(() => {});
229
+ }
230
+ }
231
+
232
+ private ready(): void {
233
+ if (this.stopped) throw new Error('Dressing importer is stopped');
234
+ if (this.pending) throw new Error('Another dressing import is in progress');
235
+ }
236
+
237
+ private run<T>(work: () => Promise<T>): Promise<T> {
238
+ const task = work().finally(() => { this.pending = null; });
239
+ this.pending = task;
240
+ return task;
241
+ }
242
+
243
+ async upload(raw: unknown, t: PetText['importing'], language: string): Promise<DressImportPreview> {
244
+ this.ready();
245
+ const files = filesFromZip(zipBytes(raw), t, ZIP_EXPANDED_MAX, zipEntryCheck());
246
+ if (typeof files === 'string') throw new Error(files);
247
+ this.stage = null;
248
+ const controller = new AbortController();
249
+ this.uploading = controller;
250
+ return this.run(async () => {
251
+ try {
252
+ const result = await this.importer.stage(files, false, { signal: controller.signal, maxPacks: ZIP_PACKS_MAX });
253
+ controller.signal.throwIfAborted();
254
+ if ('error' in result) throw new Error(result.error);
255
+ if (result.packs.some((p) => DEVICE_NAME.test(p.id))) throw new Error('Figure ID is a reserved filename');
256
+ const preview = {
257
+ token: result.token,
258
+ packs: result.packs.map((p) => ({ dir: p.dir, id: p.id, name: nameIn(p.name, language).slice(0, LABEL_MAX), installed: p.installed?.slice(0, LABEL_MAX) ?? null })),
259
+ problems: result.problems.map(({ dir, reason }) => ({ dir, reason: reason.slice(0, 512) })),
260
+ };
261
+ this.stage = result.token ? { token: result.token, ids: new Map(result.packs.map((p) => [p.dir, p.id])) } : null;
262
+ return preview;
263
+ } catch (err) {
264
+ await this.importer.cancel();
265
+ throw err;
266
+ } finally {
267
+ this.uploading = null;
268
+ }
269
+ });
270
+ }
271
+
272
+ async install(token: unknown, rawDirs: unknown, rawReplace: unknown, t: PetText['importing']): Promise<{ installed: string[] } | { conflicts: string[] }> {
273
+ this.ready();
274
+ const stage = this.stage;
275
+ if (!stage || token !== stage.token) throw new Error(t.expired);
276
+ if (!Array.isArray(rawDirs) || rawDirs.length > stage.ids.size || !rawDirs.length) throw new Error(t.noneChosen);
277
+ const selected = new Set<string>();
278
+ for (const dir of rawDirs) {
279
+ if (typeof dir !== 'string' || selected.has(dir) || !stage.ids.has(dir)) throw new Error('Unknown or duplicate staged directory');
280
+ selected.add(dir);
281
+ }
282
+ const selectedIds = new Set(Array.from(selected, (dir) => stage.ids.get(dir)!));
283
+ if (rawReplace !== undefined && (!Array.isArray(rawReplace) || rawReplace.length > selected.size)) throw new Error('Invalid replacement list');
284
+ const replace = new Set<string>();
285
+ for (const id of (rawReplace as unknown[] | undefined) ?? []) {
286
+ if (typeof id !== 'string' || replace.has(id) || !selectedIds.has(id)) throw new Error('Unknown or duplicate replacement ID');
287
+ replace.add(id);
288
+ }
289
+ return this.run(async () => {
290
+ try {
291
+ const result = await this.importer.install(stage.token, [...selected], [...replace], { protectOtherPacks: true });
292
+ if ('error' in result) throw new Error(result.error);
293
+ if ('installed' in result) this.stage = null;
294
+ return result;
295
+ } catch (err) {
296
+ this.stage = null;
297
+ await this.importer.cancel();
298
+ throw err;
299
+ }
300
+ });
301
+ }
302
+
303
+ async cancel(token: unknown): Promise<null> {
304
+ if (typeof token !== 'string' || token.length > 36) throw new Error('Invalid dressing import token');
305
+ if (this.stage?.token === token) {
306
+ this.stage = null;
307
+ await this.importer.cancel();
308
+ }
309
+ return null;
310
+ }
311
+ }
@@ -14,7 +14,7 @@ import { randomUUID } from 'node:crypto';
14
14
  import { existsSync } from 'node:fs';
15
15
  import { cp, mkdir, mkdtemp, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises';
16
16
  import { tmpdir } from 'node:os';
17
- import { extname, join, normalize, sep } from 'node:path';
17
+ import { extname, join, normalize, resolve, sep } from 'node:path';
18
18
  import { unzipSync } from 'fflate';
19
19
  import { MANIFEST_FILE, readManifest, type FigurePack, type Names } from './packs.ts';
20
20
  import { petText, type PetText } from './i18n/index.ts';
@@ -65,11 +65,12 @@ function segments(path: string): string[] | null {
65
65
  }
66
66
 
67
67
  /** The files of a zip, its directories left out; a string says why it cannot be read. */
68
- export function filesFromZip(bytes: Uint8Array, t: PetText['importing'] = petText().importing, expandedLimit?: number): ImportFile[] | string {
68
+ export function filesFromZip(bytes: Uint8Array, t: PetText['importing'] = petText().importing, expandedLimit?: number, checkEntry?: (name: string, bytes: number) => void): ImportFile[] | string {
69
69
  let entries: Record<string, Uint8Array>;
70
70
  try {
71
71
  let expanded = 0;
72
72
  entries = unzipSync(bytes, { filter: (f) => {
73
+ checkEntry?.(f.name, Math.max(f.size, f.originalSize));
73
74
  if (f.name.endsWith('/')) return false;
74
75
  if (expandedLimit !== undefined) {
75
76
  expanded += Math.max(f.size, f.originalSize);
@@ -139,31 +140,56 @@ export class PackImporter {
139
140
  private staged: { token: string; root: string; packs: StagedPack[] } | null = null;
140
141
 
141
142
  /** `text`: the text table of the app language, for what goes wrong; Chinese when absent. */
142
- constructor(private readonly opts: { packDir: () => string; packs: () => FigurePack[]; text?: () => PetText }) {}
143
+ constructor(
144
+ private readonly opts: { packDir: () => string; packs: () => FigurePack[]; text?: () => PetText },
145
+ private readonly writes = { tail: Promise.resolve() },
146
+ ) {}
147
+
148
+ /** Another surface owns its own stage and tokens but writes to the same installed pack directory. */
149
+ isolated(): PackImporter {
150
+ return new PackImporter(this.opts, this.writes);
151
+ }
152
+
153
+ private write<T>(fn: () => Promise<T>): Promise<T> {
154
+ const work = this.writes.tail.then(fn);
155
+ this.writes.tail = work.then(() => {}, () => {});
156
+ return work;
157
+ }
143
158
 
144
159
  private get t(): PetText {
145
160
  return this.opts.text?.() ?? petText();
146
161
  }
147
162
 
148
163
  /** Unpacks `files` into a staging directory and reads the packs in it; `fromFolders`: each file's path starts with the folder picked. */
149
- async stage(files: ImportFile[], fromFolders: boolean): Promise<StageResult | { error: string }> {
164
+ async stage(files: ImportFile[], fromFolders: boolean, options?: { signal: AbortSignal; maxPacks: number }): Promise<StageResult | { error: string }> {
150
165
  await this.cancel();
166
+ options?.signal.throwIfAborted();
151
167
  const root = await mkdtemp(join(tmpdir(), 'figure-import-'));
152
168
  try {
153
169
  for (const f of files) {
170
+ options?.signal.throwIfAborted();
154
171
  const parts = segments(f.path);
155
172
  if (!parts) { await rm(root, { recursive: true, force: true }); return { error: this.t.importing.badPath(f.path) }; }
156
173
  await mkdir(join(root, ...parts.slice(0, -1)), { recursive: true });
157
- await writeFile(join(root, ...parts), f.bytes);
174
+ await writeFile(join(root, ...parts), f.bytes, { signal: options?.signal });
158
175
  }
159
176
  const dirs = await findPacks(root, PACK_DEPTH + (fromFolders ? 1 : 0));
177
+ if (options && dirs.length > options.maxPacks) throw new Error(`Too many packs (maximum ${options.maxPacks})`);
160
178
  const installed = this.opts.packs();
161
179
  const packs: StagedPack[] = [];
162
180
  const problems: StageResult['problems'] = [];
163
181
  for (const dir of dirs) {
164
182
  const full = join(root, ...dir.split('/').filter(Boolean));
165
183
  const skipped: string[] = [];
166
- const m = readManifest(full, false, skipped, this.t.packs);
184
+ options?.signal.throwIfAborted();
185
+ let m;
186
+ try {
187
+ m = readManifest(full, false, skipped, this.t.packs);
188
+ } catch (err) {
189
+ if (!options) throw err;
190
+ problems.push({ dir, reason: this.t.packs.badJson(MANIFEST_FILE, (err as Error).message) });
191
+ continue;
192
+ }
167
193
  if (typeof m === 'string') { problems.push({ dir, reason: m }); continue; }
168
194
  const same = installed.find((p) => p.id === m.id);
169
195
  if (same?.builtin) { problems.push({ dir, reason: this.t.importing.builtinId(m.id) }); continue; }
@@ -171,10 +197,11 @@ export class PackImporter {
171
197
  packs.push({
172
198
  dir, id: m.id, name: m.name, version: m.version, author: m.author ?? null,
173
199
  credits: (m.credits ?? []).filter((c) => typeof c?.role === 'string' && typeof c?.name === 'string').map(({ role, name }) => ({ role, name })),
174
- thumb: await thumbOf(full, m.thumb), axes: m.axes.length, words: m.vocab.length, sounds: Object.keys(m.sounds).length,
200
+ thumb: options ? null : await thumbOf(full, m.thumb), axes: m.axes.length, words: m.vocab.length, sounds: Object.keys(m.sounds).length,
175
201
  skipped, installed: same ? same.manifest.version : null,
176
202
  });
177
203
  }
204
+ options?.signal.throwIfAborted();
178
205
  if (!packs.length) await rm(root, { recursive: true, force: true });
179
206
  else this.staged = { token: randomUUID(), root, packs };
180
207
  return { token: this.staged?.token ?? '', packs, problems };
@@ -185,7 +212,11 @@ export class PackImporter {
185
212
  }
186
213
 
187
214
  /** A conflict leaves every pack untouched and the token valid; `replace` names the ids approved for replacement. */
188
- async install(token: string, dirs: readonly string[], replace: readonly string[] = []): Promise<{ installed: string[] } | { conflicts: string[] } | { error: string }> {
215
+ install(token: string, dirs: readonly string[], replace: readonly string[] = [], options?: { protectOtherPacks: boolean }): Promise<{ installed: string[] } | { conflicts: string[] } | { error: string }> {
216
+ return this.write(() => this.installStaged(token, dirs, replace, options?.protectOtherPacks ?? false));
217
+ }
218
+
219
+ private async installStaged(token: string, dirs: readonly string[], replace: readonly string[], protectOtherPacks: boolean): Promise<{ installed: string[] } | { conflicts: string[] } | { error: string }> {
189
220
  const staged = this.staged;
190
221
  if (!staged || staged.token !== token) return { error: this.t.importing.expired };
191
222
  const chosen = staged.packs.filter((p) => dirs.includes(p.dir));
@@ -194,6 +225,20 @@ export class PackImporter {
194
225
  const installed = this.opts.packs();
195
226
  const builtin = chosen.find((p) => installed.some((x) => x.id === p.id && x.builtin));
196
227
  if (builtin) return { error: this.t.importing.builtinId(builtin.id) };
228
+ if (protectOtherPacks) {
229
+ const canonical = (dir: string) => resolve(dir).normalize('NFD').toLowerCase();
230
+ for (const p of chosen) {
231
+ const target = canonical(join(packDir, p.id));
232
+ const old = installed.find((x) => x.id === p.id && this.removable(x));
233
+ const destinations = old ? [target, canonical(old.dir)] : [target];
234
+ const overlaps = installed.some((x) => {
235
+ if (x.id === p.id) return false;
236
+ const dir = canonical(x.dir);
237
+ return destinations.some((dest) => dir === dest || within(dir, dest) || within(dest, dir));
238
+ });
239
+ if (overlaps) return { error: 'The install path overlaps another figure pack' };
240
+ }
241
+ }
197
242
  const conflicts = chosen.filter((p) => installed.some((x) => x.id === p.id) || existsSync(join(packDir, p.id))).map((p) => p.id);
198
243
  if (conflicts.some((id) => !replace.includes(id))) return { conflicts };
199
244
  // Consume the token before writing so concurrent installs cannot reuse it.
@@ -222,7 +267,11 @@ export class PackImporter {
222
267
  }
223
268
 
224
269
  /** Deletes the directory of the installed pack `id`; the next scan no longer lists it. */
225
- async remove(id: string): Promise<{ removed: string } | { error: string }> {
270
+ remove(id: string): Promise<{ removed: string } | { error: string }> {
271
+ return this.write(() => this.removeInstalled(id));
272
+ }
273
+
274
+ private async removeInstalled(id: string): Promise<{ removed: string } | { error: string }> {
226
275
  const pack = this.opts.packs().find((p) => p.id === id);
227
276
  if (!pack) return { error: this.t.removing.notInstalled(id) };
228
277
  if (pack.builtin) return { error: this.t.removing.builtin(id) };
@@ -11,14 +11,13 @@ import { petText } from '../i18n/index.ts';
11
11
  import { describeHostReason, type HostReason } from '../host-reason.ts';
12
12
  import { captureKey, PRESSES, splitTaps, withTaps } from './key-capture.ts';
13
13
  import { apiRows, type ApiState } from './api-rows.ts';
14
- import { hostFrameDressDialogs } from './dress-dialog.ts';
14
+ import { mountDress } from './dress.ts';
15
15
  import './style.css';
16
16
 
17
17
  interface Artifact { phase: 'absent' | 'working' | 'ready' | 'error'; path: string; done: number; total: number | null; detail: string | null }
18
18
  interface PetState {
19
19
  inWindow: boolean;
20
20
  url: string | null;
21
- dressUrl: string | null;
22
21
  window: { phase: string; pid: number | null; source: string | null; reason: HostReason | null } | null;
23
22
  electron: Artifact & { supported: boolean };
24
23
  screen: { w: number; h: number } | null;
@@ -114,70 +113,7 @@ const petPanel: WebUiPanel = {
114
113
 
115
114
  const dress = ui.sheet({ title: t.dress, desc: t.dressHint });
116
115
  root.appendChild(dress.el);
117
- const doc = root.ownerDocument;
118
- const frame = ui.h('iframe', 'pet-dressframe');
119
- frame.title = t.dress;
120
- frame.hidden = true;
121
- const dressStatus = ui.h('div', 'read-feedback');
122
- dressStatus.setAttribute('role', 'status');
123
- dress.body.append(dressStatus, frame);
124
- hostFrameDressDialogs({ doc, host: doc.body, signal: ctx.signal }, frame);
125
-
126
- const appearance = () => {
127
- const mode = doc.documentElement.dataset.colorMode;
128
- return mode === 'dark' || (!mode && matchMedia('(prefers-color-scheme: dark)').matches) ? 'dark' : 'light';
129
- };
130
- const syncAppearance = () => {
131
- if (!frame.dataset.origin) return;
132
- const accent = getComputedStyle(doc.documentElement).getPropertyValue('--accent').trim();
133
- frame.contentWindow?.postMessage({ type: 'companion:appearance', mode: appearance(), accent }, frame.dataset.origin);
134
- };
135
- const observer = new MutationObserver(syncAppearance);
136
- observer.observe(doc.documentElement, { attributes: true, attributeFilter: ['data-color-mode', 'data-theme-scheme'] });
137
- ctx.own({ dispose: () => observer.disconnect() });
138
- frame.addEventListener('load', syncAppearance, { signal: ctx.signal });
139
- const zh = ctx.language === 'zh' || ctx.language === 'zh-Hant';
140
- let pending: { dispose(): void } | undefined;
141
- doc.defaultView?.addEventListener('message', (event) => {
142
- if (event.source !== frame.contentWindow || event.origin !== frame.dataset.origin) return;
143
- if (event.data?.type === 'companion:height') {
144
- const height = event.data.height;
145
- if (Number.isFinite(height) && height > 0) frame.style.height = `${height}px`;
146
- } else if (event.data?.type === 'companion:painted') {
147
- pending?.dispose();
148
- dressStatus.hidden = true;
149
- frame.hidden = false;
150
- frame.classList.remove('pet-dressframe-pending');
151
- }
152
- }, { signal: ctx.signal });
153
- const showDress = (url: string | null) => {
154
- if ((frame.dataset.src ?? null) === url) return;
155
- pending?.dispose();
156
- dressStatus.hidden = false;
157
- if (url === null) {
158
- frame.hidden = true;
159
- delete frame.dataset.src;
160
- delete frame.dataset.origin;
161
- frame.removeAttribute('src');
162
- dressStatus.textContent = zh ? '装扮服务尚未就绪。' : 'Dressing is not ready yet.';
163
- return;
164
- }
165
- const target = new URL(url);
166
- frame.dataset.src = url;
167
- frame.dataset.origin = target.origin;
168
- target.searchParams.set('appearance', appearance());
169
- target.searchParams.set('fit', '1');
170
- frame.classList.add('pet-dressframe-pending');
171
- frame.hidden = false;
172
- dressStatus.textContent = zh ? '正在加载装扮…' : 'Loading dressing…';
173
- pending = ctx.timeout(() => {
174
- if (!frame.classList.contains('pet-dressframe-pending')) return;
175
- frame.hidden = true;
176
- dressStatus.textContent = zh ? '无法加载内嵌装扮。请确认 Coopanion 支持 Agent Speed 内嵌装扮。'
177
- : 'Could not load inline dressing. Check that this version of Coopanion supports Agent Speed inline dressing.';
178
- }, 8000);
179
- frame.src = target.href;
180
- };
116
+ mountDress(ctx, dress.body);
181
117
 
182
118
  s.append(win.row, rt.row);
183
119
  dress.el.hidden = true;
@@ -201,7 +137,6 @@ const petPanel: WebUiPanel = {
201
137
  else rt.set(e.supported ? t.notInstalled : t.noBuild, 'off', e.supported ? t.electronSize : '');
202
138
  btnInstall.hidden = e.phase === 'ready' || !e.supported;
203
139
  btnInstall.disabled = e.phase === 'working';
204
- showDress(next.dressUrl);
205
140
  };
206
141
  const refresh = async () => { try { render(await ctx.invoke<PetState>('state')); } catch (err) { if (!ctx.signal.aborted) msg.replaceChildren(listProblem(root.ownerDocument, errText(err))); } };
207
142
  const call = (method: string, anchor: HTMLElement) => async () => {
@@ -0,0 +1,42 @@
1
+ .own-dress{--dress-surface:var(--sheet, #fff);--dress-line:var(--line, #e2dfe8);--dress-text:var(--ink, #1b1626);--dress-muted:var(--ink-soft, #6a6577);--dress-accent:var(--accent, #00a870);color:var(--dress-text)}
2
+ .own-dress-content{display:flex;flex-direction:column;gap:20px}
3
+ .own-dress-status{font-size:13px;color:var(--dress-muted);margin-bottom:12px}
4
+ .own-dress-status[hidden]{display:none}
5
+ .own-dress-retry{font:inherit;color:var(--dress-accent);border:0;background:none;text-decoration:underline;cursor:pointer}
6
+ .own-dress-stage{position:relative;height:300px;overflow:hidden;border:1px solid #252c37;border-radius:12px;background:#10151c radial-gradient(#232b37 1.2px,transparent 1.3px) 0 0 / 22px 22px}
7
+ .own-dress-stage[data-theme=light]{border-color:#e2dfe8;background-color:#e8e6ee;background-image:radial-gradient(#cfcbd9 1.2px,transparent 1.3px)}
8
+ .own-dress-floor{position:absolute;bottom:0;left:0;right:0;height:48px;border-top:1px solid #252c37;background:#151a22}
9
+ .own-dress-stage[data-theme=light] .own-dress-floor{border-color:#e2dfe8;background:#fff}
10
+ .own-dress-art{position:absolute;inset:25px 0 48px;display:flex;align-items:flex-end;justify-content:center;pointer-events:none}
11
+ .own-dress-art svg,.own-dress-art img{width:190px;height:190px;object-fit:contain}
12
+ .own-dress-corner{position:absolute;top:12px;right:12px;display:flex;gap:8px}
13
+ .own-dress-round{display:grid;place-items:center;width:34px;height:34px;padding:0;border:1px solid #252c37;border-radius:50%;background:#151a22;color:#e9edf2;font:inherit;font-size:21px;cursor:pointer}
14
+ .own-dress-stage[data-theme=light] .own-dress-round{background:#fff;border-color:#e2dfe8;color:#1b1626}
15
+ .own-dress-round:hover{border-color:var(--dress-accent);color:var(--dress-accent)}
16
+ .own-dress-theme{position:absolute;top:12px;left:12px;font-size:17px}
17
+ .own-dress-grid{display:grid;grid-template-columns:minmax(4.5em,max-content) minmax(0,1fr);gap:12px 14px;align-items:start}
18
+ .own-dress-heading{grid-column:1/-1;margin:10px 0 0;padding-top:22px;border-top:1px solid var(--dress-line);font-size:15px;font-weight:600;line-height:1.4}
19
+ .own-dress-heading.first{margin-top:4px;padding-top:0;border-top:0}
20
+ .own-dress-looks{grid-column:1/-1;display:flex;gap:8px;overflow-x:auto;padding:2px}
21
+ .own-dress-empty{margin:0;color:var(--dress-muted);font-size:13px;line-height:1.5}
22
+ .own-dress-label{padding-top:18px;font-size:14px;color:var(--dress-muted)}
23
+ .own-dress-options{display:flex;flex-wrap:wrap;gap:8px;min-width:0}
24
+ .own-dress-tile{display:flex;flex:none;flex-direction:column;align-items:center;gap:2px;min-width:72px;max-width:116px;padding:8px 4px 6px;border:1px solid var(--dress-line);border-radius:10px;background:var(--dress-surface);color:var(--dress-text);font:inherit;cursor:pointer}
25
+ .own-dress-tile:hover,.own-dress-tile[aria-pressed=true]{border-color:var(--dress-accent)}
26
+ .own-dress-tile[aria-pressed=true]{background:color-mix(in srgb,var(--dress-accent) 14%,var(--dress-surface))}
27
+ .own-dress-tile svg,.own-dress-tile img,.own-dress-plus{display:block;width:52px;height:52px;border-radius:6px;background:color-mix(in srgb,var(--dress-text) 6%,var(--dress-surface));object-fit:cover}
28
+ .own-dress-tile span:not(.own-dress-plus){max-width:100%;font-size:12px;line-height:1.25;overflow-wrap:anywhere;text-align:center}
29
+ .own-dress-figure{width:116px}.own-dress-import{border-style:dashed}.own-dress-plus{display:grid;place-items:center;color:var(--dress-muted);font-size:28px;font-weight:300}
30
+ .own-dress-look{position:relative;display:flex;flex:none}.own-dress-remove{position:absolute;top:4px;right:4px;width:22px;height:22px;padding:0;border:0;border-radius:6px;background:var(--dress-surface);color:var(--dress-muted);font-size:18px;cursor:pointer;opacity:0}.own-dress-look:hover .own-dress-remove,.own-dress-look:focus-within .own-dress-remove{opacity:1}
31
+ .own-dress-size{align-items:center;min-height:40px;gap:14px;color:var(--dress-muted);font-size:13px;font-variant-numeric:tabular-nums}.own-dress-size input{width:min(280px,75%);accent-color:var(--dress-accent)}
32
+ .own-dress button:focus-visible,.own-dress input:focus-visible{outline:2px solid var(--dress-accent);outline-offset:2px}
33
+ .own-dress svg .ink{stroke:var(--skin-ink)}.own-dress svg .inkf{fill:var(--skin-ink)}.own-dress svg .eye{stroke:var(--skin-eye)}
34
+ .own-dress svg .blush{fill:#ff8fa8}.own-dress svg .tearf{fill:#5aaef0}.own-dress svg .angry{stroke:#e5484d}
35
+ .own-dress svg .c-head-main{stroke:var(--c-head-main,var(--skin-ink))}.own-dress svg .c-head-acc{stroke:var(--c-head-acc,var(--skin-eye))}
36
+ .own-dress svg .c-glasses-main{stroke:var(--c-glasses-main,var(--skin-ink))}.own-dress svg .c-glasses-acc{stroke:var(--c-glasses-acc,var(--skin-eye))}
37
+ .own-dress svg .c-side-main{stroke:var(--c-side-main,var(--skin-eye))}.own-dress svg .c-side-acc{stroke:var(--c-side-acc,var(--skin-eye))}
38
+ .own-dress svg .c-neck-main{stroke:var(--c-neck-main,var(--skin-eye))}.own-dress svg .c-neck-acc{stroke:var(--c-neck-acc,var(--skin-eye))}
39
+ .own-dress svg .f-head-main{fill:var(--c-head-main,var(--skin-ink))}.own-dress svg .f-head-acc{fill:var(--c-head-acc,var(--skin-eye))}
40
+ .own-dress svg .f-side-main{fill:var(--c-side-main,var(--skin-eye))}.own-dress svg .f-side-acc{fill:var(--c-side-acc,var(--skin-eye))}
41
+ .own-dress svg .f-neck-main{fill:var(--c-neck-main,var(--skin-eye))}.own-dress svg .f-neck-acc{fill:var(--c-neck-acc,var(--skin-eye))}
42
+ @media(max-width:640px){.own-dress-grid{grid-template-columns:1fr;gap:8px}.own-dress-label{padding-top:8px}.own-dress-stage{height:260px}.own-dress-heading{padding-top:18px}}