editmamei 0.23.0 → 1.0.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.
Files changed (90) hide show
  1. package/NOTICES.md +6 -30
  2. package/README.md +47 -13
  3. package/dist/api/extendscript/_helpers.js +1 -101
  4. package/dist/api/photoshop-api.js +23 -16
  5. package/dist/api/snippet-client.js +38 -2
  6. package/dist/bin/editmamei-core-darwin-arm64 +0 -0
  7. package/dist/bin/editmamei-core-darwin-x64 +0 -0
  8. package/dist/bin/editmamei-core-win-x64.exe +0 -0
  9. package/dist/core/server.js +60 -184
  10. package/dist/core/session.js +9 -10
  11. package/dist/core/tool-registry.js +4 -4
  12. package/dist/delivery/client.js +50 -1
  13. package/dist/delivery/provision.js +18 -1
  14. package/dist/delivery/signing.js +38 -1
  15. package/dist/delivery/store.js +157 -16
  16. package/dist/detection/detect-active-doc.js +42 -11
  17. package/dist/detection/detection-client.js +3 -3
  18. package/dist/detection/face-detector.js +2 -2
  19. package/dist/detection/geometry.js +14 -0
  20. package/dist/detection/landmark-detection-client.js +3 -3
  21. package/dist/detection/mesh-face.js +2 -3
  22. package/dist/detection/object-detector.js +2 -2
  23. package/dist/detection/runtime.js +14 -3
  24. package/dist/detection/sam-segmenter.js +69 -26
  25. package/dist/kernel/kernel.js +5 -9
  26. package/dist/kernel/module-lifecycle.js +187 -0
  27. package/dist/license/entitlement.js +13 -3
  28. package/dist/license/store.js +8 -1
  29. package/dist/modules/ce/index.js +1 -1
  30. package/dist/perception/facets.js +19 -1
  31. package/dist/perception/grounding-anchors.js +2 -12
  32. package/dist/perception/grounding-locate.js +1 -9
  33. package/dist/perception/grounding-review-crop.js +4 -29
  34. package/dist/perception/overlay.js +62 -0
  35. package/dist/perception/pixel-identity.js +41 -0
  36. package/dist/perception/region-precompute.js +96 -20
  37. package/dist/perception/scene-model.js +93 -50
  38. package/dist/perception/select-recipes.js +109 -68
  39. package/dist/perception/sky-ground-flood.js +0 -5
  40. package/dist/perception/sky-mask-transfer.js +73 -14
  41. package/dist/platform/connection.js +60 -43
  42. package/dist/platform/host-platform.js +16 -0
  43. package/dist/platform/macos-detector.js +41 -70
  44. package/dist/platform/macos-runner.js +94 -0
  45. package/dist/platform/script-queue.js +68 -0
  46. package/dist/platform/script-result.js +39 -0
  47. package/dist/platform/windows-detector.js +49 -66
  48. package/dist/platform/windows-runner.js +84 -0
  49. package/dist/skills/editmamei-skill.zip +0 -0
  50. package/dist/tools/adjustment-tools.js +80 -132
  51. package/dist/tools/brush-tools.js +4 -15
  52. package/dist/tools/channel-compose-tools.js +4 -23
  53. package/dist/tools/detection-tools.js +59 -47
  54. package/dist/tools/document-tools.js +92 -127
  55. package/dist/tools/filter-tools.js +490 -731
  56. package/dist/tools/group-tools.js +75 -156
  57. package/dist/tools/guide-tools.js +52 -83
  58. package/dist/tools/history-tools.js +29 -63
  59. package/dist/tools/image-placement-tools.js +18 -37
  60. package/dist/tools/image-tools.js +23 -51
  61. package/dist/tools/layer-ordering-tools.js +2 -9
  62. package/dist/tools/layer-properties-tools.js +207 -395
  63. package/dist/tools/layer-tools.js +224 -190
  64. package/dist/tools/layer-transform-tools.js +41 -106
  65. package/dist/tools/metadata-tools.js +2 -9
  66. package/dist/tools/path-tools.js +4 -15
  67. package/dist/tools/portrait-tools.js +2 -5
  68. package/dist/tools/preview-tools.js +59 -72
  69. package/dist/tools/retouch-tools.js +33 -71
  70. package/dist/tools/scene-tools.js +123 -75
  71. package/dist/tools/selection-tools.js +386 -566
  72. package/dist/tools/shape-tools.js +2 -9
  73. package/dist/tools/text-tools.js +24 -57
  74. package/dist/tools/transform-canvas-tools.js +21 -54
  75. package/dist/tools/vector-mask-tools.js +2 -9
  76. package/dist/update/check.js +1 -1
  77. package/dist/utils/jpeg-quality.js +1 -0
  78. package/dist/utils/logger.js +55 -45
  79. package/dist/utils/operation-timeouts.js +1 -0
  80. package/dist/utils/run-script.js +7 -2
  81. package/dist/utils/session-log.js +134 -12
  82. package/dist/utils/template-storage.js +5 -6
  83. package/dist/utils/tool-helpers.js +43 -0
  84. package/dist/version.js +1 -1
  85. package/package.json +10 -3
  86. package/LICENSE +0 -81
  87. package/dist/platform/detector.js +0 -32
  88. package/dist/platform/macos-executor.js +0 -151
  89. package/dist/platform/windows-executor.js +0 -160
  90. /package/dist/platform/{script-executor.js → ports.js} +0 -0
@@ -13,30 +13,18 @@ import { loadSettings, applyTelemetryEnvOverrides, applyUpdateCheckEnvOverride,
13
13
  import { TelemetryClient } from '../telemetry/client.js';
14
14
  import { resolveInstallChannel } from '../install-channel.js';
15
15
  import { checkForUpdate, shouldCheckForUpdate } from '../update/check.js';
16
- import { join, dirname } from 'node:path';
17
- import { pathToFileURL } from 'node:url';
18
- import { GoSnippetClient, resolveProBinaryPath, coreBinaryName } from '../api/snippet-client.js';
16
+ import { join } from 'node:path';
17
+ import { GoSnippetClient, coreBinaryName } from '../api/snippet-client.js';
19
18
  import { isProEntitled } from '../license/entitlement.js';
20
19
  import { createPingLicenseRefresher } from '../license/ping-refresh.js';
21
- import { loadVerifiedModule, readInstalledModule, installedPath, PRO_SKU, } from '../delivery/store.js';
22
- import { provisionModules } from '../delivery/provision.js';
23
- import { readLicense } from '../license/store.js';
24
- import { existsSync } from 'node:fs';
25
20
  import { runScript } from '../utils/run-script.js';
26
21
  import { listTemplates } from '../utils/template-storage.js';
22
+ import { toolErrorResult } from '../utils/tool-helpers.js';
27
23
  import { Kernel } from '../kernel/kernel.js';
28
- import { HOST_MIN_ABI } from '../kernel/host-api.js';
29
24
  import { ceModule } from '../modules/ce/index.js';
30
25
  import { hostDetectionRuntime } from '../detection/runtime.js';
31
- export function classifyModuleOutcome(inputs) {
32
- if (inputs.proModuleLoaded && inputs.skipReason === null)
33
- return 'loaded';
34
- if (inputs.skipReason === 'corrupt')
35
- return 'skipped_corrupt';
36
- if (inputs.skipReason === 'incompatible')
37
- return 'skipped_incompatible';
38
- return inputs.entitled ? 'absent' : 'lapsed';
39
- }
26
+ import { ModuleLifecycle, classifyModuleOutcome } from '../kernel/module-lifecycle.js';
27
+ export { classifyModuleOutcome };
40
28
  let logScriptOnErrorWarned = false;
41
29
  function warnLogScriptOnErrorOnce(logger) {
42
30
  if (logScriptOnErrorWarned)
@@ -64,8 +52,10 @@ export class EditmameiServer {
64
52
  sessionLog;
65
53
  telemetry;
66
54
  kernel;
67
- proModule = null;
68
- moduleSkipReason = null;
55
+ moduleLifecycle;
56
+ get moduleSkipReason() {
57
+ return this.moduleLifecycle.moduleSkipReason;
58
+ }
69
59
  psVersion = null;
70
60
  updateInfo = null;
71
61
  snippetClient = new GoSnippetClient();
@@ -134,7 +124,7 @@ export class EditmameiServer {
134
124
  this.toolRegistry.register('ps_ping', {
135
125
  tool: {
136
126
  name: 'ps_ping',
137
- description: 'Test connection to Photoshop and report session-start discovery signals. Read-only and idempotent. Call this once at the start of a session to confirm liveness before invoking any other tool. **If the user has given you an open-ended editing task, ALSO call `ps_overview` after this** — it returns the workflow contract + capabilities map + verification primitives so you can plan well. Returns `version` (folds the deleted photoshop_get_version), `custom_action_sets` (count of Action Sets loaded in the Photoshop Actions palette — non-zero means recorded workflows exist; if action tools are available in this build they will appear in `tools/list`), `user_templates` (count of saved Editmamei templates), and `open_documents` (names of documents already open in Photoshop, so the LLM does not have to ask which doc to edit).',
127
+ description: 'Test connection to Photoshop and report session-start discovery signals. Read-only and idempotent. Call this once at the start of a session to confirm liveness before invoking any other tool. **If the user has given you an open-ended editing task, ALSO call `ps_overview` after this** — it returns the workflow contract + capabilities map + verification primitives so you can plan well. Returns `version` (folds the removed get-version tool), `custom_action_sets` (count of Action Sets loaded in the Photoshop Actions palette — non-zero means recorded workflows exist; if action tools are available in this build they will appear in `tools/list`), `user_templates` (count of saved Editmamei templates), and `open_documents` (names of documents already open in Photoshop, so the LLM does not have to ask which doc to edit).',
138
128
  inputSchema: {
139
129
  type: 'object',
140
130
  properties: {},
@@ -150,7 +140,7 @@ export class EditmameiServer {
150
140
  degraded: {
151
141
  type: 'array',
152
142
  items: { type: 'string' },
153
- description: 'List of optional discovery signals that could not be gathered (e.g. "pingState" if the in-PS state snippet failed, "templates" if ~/.editmamei/templates was unreadable). Empty when all signals were collected cleanly. Returned defaults for any degraded field cannot be trusted as ground truth.',
143
+ description: 'List of optional discovery signals that could not be gathered (e.g. "pingState" if the go-core snippet builder itself failed to produce the in-PS state script — a broken/missing local install, unrelated to whether Photoshop is reachable; liveness falls back to a cheap ping probe in that case — "templates" if ~/.editmamei/templates was unreadable). Empty when all signals were collected cleanly. Returned defaults for any degraded field cannot be trusted as ground truth.',
154
144
  },
155
145
  update_available: {
156
146
  type: ['object', 'null'],
@@ -204,162 +194,39 @@ export class EditmameiServer {
204
194
  },
205
195
  handler: async () => this.listCapabilities(),
206
196
  });
207
- this.proModule = this.resolveProModule();
197
+ this.moduleLifecycle = new ModuleLifecycle({
198
+ toolRegistry: this.toolRegistry,
199
+ logger: this.logger,
200
+ assertToolsClassified: () => this.assertToolsClassified(),
201
+ });
202
+ const proModule = this.moduleLifecycle.resolveProModule();
208
203
  this.kernel = new Kernel({
209
204
  registry: this.toolRegistry,
210
205
  connection: this.session.getConnection(),
211
206
  snippet: this.snippetClient,
212
207
  detection: hostDetectionRuntime(),
213
- resolveModuleSnippet: (manifest) => manifest.goCoreSnippets && manifest.goCoreSnippets.length > 0 && this.proModule
214
- ? new GoSnippetClient({ binaryPath: join(this.proModule.binDir, coreBinaryName()) })
208
+ resolveModuleSnippet: (manifest) => manifest.goCoreSnippets && manifest.goCoreSnippets.length > 0 && proModule
209
+ ? new GoSnippetClient({ binaryPath: join(proModule.binDir, coreBinaryName()) })
215
210
  : null,
216
211
  sessionId: this.session.getSessionId(),
217
212
  logger: this.logger,
218
213
  });
214
+ this.moduleLifecycle.setKernel(this.kernel);
219
215
  this.kernel.loadBuiltins([ceModule]);
220
216
  this.assertToolsClassified();
221
217
  this.logger.info(`Registered ${this.toolRegistry.count()} tools (edition: ${EDITION})`);
222
218
  }
223
- resolveProModule() {
224
- if (isProEntitled()) {
225
- const verified = loadVerifiedModule(PRO_SKU);
226
- if (verified) {
227
- const abi = readInstalledModule(PRO_SKU)?.abi ?? null;
228
- return {
229
- importer: () => import(pathToFileURL(verified.handlersPath).href),
230
- binDir: verified.binDir,
231
- abi,
232
- };
233
- }
234
- if (EDITION !== 'dev' && existsSync(installedPath(PRO_SKU))) {
235
- this.moduleSkipReason = 'corrupt';
236
- }
237
- }
238
- if (EDITION === 'dev') {
239
- return {
240
- importer: () => import('../modules/pro/index.js'),
241
- binDir: dirname(resolveProBinaryPath()),
242
- abi: null,
243
- };
244
- }
245
- return null;
246
- }
247
219
  async loadModules() {
248
- if (!this.proModule)
249
- return;
250
- if (this.proModule.abi !== null && this.proModule.abi < HOST_MIN_ABI) {
251
- this.logger.warn(`Pro module (abi ${this.proModule.abi}) is older than this host requires ` +
252
- `(min abi ${HOST_MIN_ABI}) — booting Community; will re-provision in the background.`);
253
- this.moduleSkipReason = 'incompatible';
254
- return;
255
- }
256
- const snapshot = this.toolRegistry.snapshot();
257
- try {
258
- await this.kernel.loadDownloaded(this.proModule.importer);
259
- this.assertToolsClassified();
260
- }
261
- catch (err) {
262
- const changed = this.toolRegistry.count() - snapshot.size;
263
- this.toolRegistry.restore(snapshot);
264
- this.logger.warn(`Pro module could not be loaded on this host — booting Community and rolling back ` +
265
- `${changed} module tool change(s); will re-provision in the background: ` +
266
- `${err instanceof Error ? err.message : String(err)}`);
267
- this.moduleSkipReason = 'incompatible';
268
- }
220
+ return this.moduleLifecycle.loadModules();
269
221
  }
270
222
  computeModuleStatus() {
271
- if (!readLicense())
272
- return null;
273
- const installed = readInstalledModule(PRO_SKU);
274
- return {
275
- module: PRO_SKU,
276
- outcome: classifyModuleOutcome({
277
- proModuleLoaded: this.proModule !== null,
278
- skipReason: this.moduleSkipReason,
279
- entitled: isProEntitled(),
280
- }),
281
- module_version: installed?.version ?? null,
282
- abi: installed?.abi ?? null,
283
- };
223
+ return this.moduleLifecycle.computeModuleStatus();
284
224
  }
285
225
  async reprovisionIfModuleSkipped(delivery = {}) {
286
- const reason = this.moduleSkipReason;
287
- if (reason === null)
288
- return;
289
- const license = readLicense();
290
- if (!license) {
291
- this.logger.warn('A Pro module was skipped but no cached license was found — staying Community. ' +
292
- 'Run `editmamei activate <key>` to restore Pro.');
293
- return;
294
- }
295
- try {
296
- const prov = await provisionModules(license.key, {
297
- force: reason === 'corrupt',
298
- config: delivery.config,
299
- fetchImpl: delivery.fetchImpl,
300
- signingKeys: delivery.signingKeys,
301
- sleep: delivery.sleep,
302
- });
303
- if (prov.installed.length > 0) {
304
- for (const m of prov.installed) {
305
- this.logger.info(`Pro module updated to v${m.version}, restart to load.`);
306
- }
307
- return;
308
- }
309
- if (prov.notConfigured) {
310
- this.logger.warn('Module delivery is not configured — staying Community.');
311
- return;
312
- }
313
- for (const e of prov.errors) {
314
- this.logger.warn(`Could not re-provision the ${e.sku} module (staying Community): ${e.message}`);
315
- }
316
- if (prov.errors.length === 0) {
317
- if (reason === 'incompatible') {
318
- this.logger.warn('The published Pro module does not yet support this host version — staying ' +
319
- 'Community. Update Editmamei when a compatible release ships; ' +
320
- '`editmamei report` files a diagnostic.');
321
- }
322
- else {
323
- this.logger.warn('Re-provision installed nothing for the corrupt Pro module — staying ' +
324
- 'Community. Try `editmamei repair`; `editmamei report` if it persists.');
325
- }
326
- }
327
- }
328
- catch (err) {
329
- this.logger.warn(`Background Pro-module re-provision failed (staying Community): ` +
330
- `${err instanceof Error ? err.message : String(err)}`);
331
- }
226
+ return this.moduleLifecycle.reprovisionIfModuleSkipped(delivery);
332
227
  }
333
228
  async ensureEntitledModuleFresh(delivery = {}) {
334
- if (this.moduleSkipReason !== null)
335
- return;
336
- if (!isProEntitled())
337
- return;
338
- const underTest = process.env.VITEST !== undefined || process.env.NODE_ENV === 'test';
339
- if (underTest && !delivery.fetchImpl)
340
- return;
341
- const license = readLicense();
342
- if (!license)
343
- return;
344
- try {
345
- const prov = await provisionModules(license.key, {
346
- config: delivery.config,
347
- fetchImpl: delivery.fetchImpl,
348
- signingKeys: delivery.signingKeys,
349
- sleep: delivery.sleep,
350
- });
351
- for (const m of prov.installed) {
352
- this.logger.info(`Pro module updated to v${m.version} — restart to load.`);
353
- }
354
- for (const e of prov.errors) {
355
- this.logger.warn(`Pro-module freshness check could not provision the ${e.sku} module ` +
356
- `(staying on the installed version): ${e.message}`);
357
- }
358
- }
359
- catch (err) {
360
- this.logger.warn(`Background Pro-module freshness check failed (staying on the installed version): ` +
361
- `${err instanceof Error ? err.message : String(err)}`);
362
- }
229
+ return this.moduleLifecycle.ensureEntitledModuleFresh(delivery);
363
230
  }
364
231
  assertToolsClassified() {
365
232
  for (const tool of this.toolRegistry.list()) {
@@ -401,13 +268,13 @@ export class EditmameiServer {
401
268
  }
402
269
  setupHandlers() {
403
270
  this.server.setRequestHandler(ListToolsRequestSchema, async () => {
404
- this.logger.debug('Listing available tools');
271
+ this.logger.debug('Reporting the registered tool surface');
405
272
  return {
406
273
  tools: this.toolRegistry.list(),
407
274
  };
408
275
  });
409
276
  this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
410
- this.logger.debug(`Tool called: ${request.params.name}`);
277
+ this.logger.debug(`Received a call for ${request.params.name}`);
411
278
  const args = request.params.arguments || {};
412
279
  return this.handleToolCall(request.params.name, args);
413
280
  });
@@ -420,29 +287,12 @@ export class EditmameiServer {
420
287
  }
421
288
  catch (error) {
422
289
  this.logger.error(`Tool execution failed: ${name}`, error);
423
- return {
424
- content: [
425
- {
426
- type: 'text',
427
- text: `Error: ${error instanceof Error ? error.message : String(error)}`,
428
- },
429
- ],
430
- isError: true,
431
- };
290
+ return toolErrorResult('Error', error);
432
291
  }
433
292
  }
434
293
  async pingPhotoshop() {
435
294
  this.refreshLicenseOnPing();
436
295
  const connection = this.session.getConnection();
437
- const isConnected = await connection.ping();
438
- if (!isConnected) {
439
- return {
440
- content: [
441
- { type: 'text', text: 'Failed to connect to Photoshop' + this.updateNote() },
442
- ],
443
- structuredContent: { connected: false, update_available: this.updateInfo },
444
- };
445
- }
446
296
  let version = 'Unknown';
447
297
  let actionSetsCount = 0;
448
298
  let openDocuments = [];
@@ -454,8 +304,37 @@ export class EditmameiServer {
454
304
  }
455
305
  catch {
456
306
  }
307
+ let pingStateSnippet = null;
457
308
  try {
458
- const state = (await runScript(connection, await this.snippetClient.build('pingState')));
309
+ pingStateSnippet = await this.snippetClient.build('pingState');
310
+ }
311
+ catch (err) {
312
+ this.logger.warn(`pingState snippet build failed (go-core binary missing/broken?): ${err instanceof Error ? err.message : String(err)}`);
313
+ const alive = await connection.ping().catch(() => false);
314
+ if (!alive) {
315
+ return {
316
+ content: [
317
+ { type: 'text', text: 'Photoshop did not respond' + this.updateNote() },
318
+ ],
319
+ structuredContent: { connected: false, update_available: this.updateInfo },
320
+ };
321
+ }
322
+ degraded.push('pingState');
323
+ }
324
+ if (pingStateSnippet !== null) {
325
+ let state;
326
+ try {
327
+ state = (await runScript(connection, pingStateSnippet));
328
+ }
329
+ catch (err) {
330
+ this.logger.warn(`pingState snippet failed: ${err instanceof Error ? err.message : String(err)}`);
331
+ return {
332
+ content: [
333
+ { type: 'text', text: 'Photoshop did not respond' + this.updateNote() },
334
+ ],
335
+ structuredContent: { connected: false, update_available: this.updateInfo },
336
+ };
337
+ }
459
338
  if (state.version)
460
339
  version = state.version;
461
340
  if (typeof state.action_sets_count === 'number')
@@ -463,10 +342,6 @@ export class EditmameiServer {
463
342
  if (Array.isArray(state.open_documents))
464
343
  openDocuments = state.open_documents;
465
344
  }
466
- catch (err) {
467
- this.logger.warn(`pingState snippet failed: ${err instanceof Error ? err.message : String(err)}`);
468
- degraded.push('pingState');
469
- }
470
345
  let userTemplates = 0;
471
346
  try {
472
347
  const templates = await listTemplates();
@@ -522,11 +397,12 @@ export class EditmameiServer {
522
397
  this.server.onclose = () => {
523
398
  void this.telemetry.shutdown();
524
399
  };
525
- this.logger.info('MCP Server connected via stdio');
400
+ this.logger.info('Editmamei is listening on stdio');
526
401
  }
527
402
  async stop() {
528
403
  await this.telemetry.shutdown();
529
404
  await this.session.disconnect();
530
- this.logger.info('MCP Server stopped');
405
+ await this.sessionLog.close();
406
+ this.logger.info('Editmamei has shut down');
531
407
  }
532
408
  }
@@ -3,10 +3,10 @@ import { PhotoshopConnection } from '../platform/connection.js';
3
3
  import { generateSessionId } from '../utils/session-log.js';
4
4
  export class Session {
5
5
  logger;
6
- connection = null;
7
6
  config;
8
- lastActivity;
9
7
  sessionId;
8
+ connection = null;
9
+ lastActivity;
10
10
  constructor(config = {}) {
11
11
  this.logger = new Logger('Session');
12
12
  this.config = { autoConnect: true, ...config };
@@ -23,30 +23,29 @@ export class Session {
23
23
  return this.sessionId;
24
24
  }
25
25
  async initialize() {
26
- this.logger.info('Initializing session...');
26
+ this.logger.info('Starting session', this.sessionId);
27
27
  if (this.config.autoConnect) {
28
28
  await this.connect();
29
29
  }
30
30
  }
31
31
  async connect() {
32
32
  try {
33
- this.logger.info('Connecting to Photoshop...');
34
- const connected = await this.ensureConnection().ping();
35
- if (connected) {
33
+ const reached = await this.ensureConnection().ping();
34
+ if (reached) {
36
35
  this.updateActivity();
37
- this.logger.info('Successfully connected to Photoshop');
36
+ this.logger.info('Photoshop is reachable');
38
37
  return true;
39
38
  }
40
- this.logger.warn('Failed to connect to Photoshop');
39
+ this.logger.warn('Photoshop did not answer');
41
40
  return false;
42
41
  }
43
42
  catch (error) {
44
- this.logger.error('Connection error:', error);
43
+ this.logger.error('Could not reach Photoshop', error);
45
44
  return false;
46
45
  }
47
46
  }
48
47
  async disconnect() {
49
- this.logger.info('Disconnecting session...');
48
+ this.logger.info('Ending session', this.sessionId);
50
49
  }
51
50
  getConnection() {
52
51
  return this.ensureConnection();
@@ -10,10 +10,10 @@ export class ToolRegistry {
10
10
  }
11
11
  register(name, definition) {
12
12
  if (this.tools.has(name)) {
13
- this.logger.warn(`Tool '${name}' already registered, overwriting`);
13
+ this.logger.warn(`Replacing an already-registered tool: ${name}`);
14
14
  }
15
15
  this.tools.set(name, definition);
16
- this.logger.debug(`Registered tool: ${name}`);
16
+ this.logger.debug(`Registered ${name}`);
17
17
  }
18
18
  registerAll(definitions) {
19
19
  for (const def of definitions) {
@@ -35,9 +35,9 @@ export class ToolRegistry {
35
35
  async execute(name, args) {
36
36
  const definition = this.tools.get(name);
37
37
  if (!definition) {
38
- throw new Error(`Tool not found: ${name}`);
38
+ throw new Error(`No tool is registered under the name '${name}'`);
39
39
  }
40
- this.logger.debug(`Executing tool: ${name}`);
40
+ this.logger.debug(`Dispatching ${name}`);
41
41
  const started = Date.now();
42
42
  let success = true;
43
43
  let error;
@@ -11,6 +11,7 @@ export class DeliveryError extends Error {
11
11
  this.name = 'DeliveryError';
12
12
  }
13
13
  }
14
+ const MAX_ARTIFACT_BYTES = 64 * 1024 * 1024;
14
15
  const USER_AGENT = 'editmamei-delivery-client/1';
15
16
  const HEADER_KEY = 'x-editmamei-license-key';
16
17
  const defaultFetch = (url, init) => fetch(url, init);
@@ -23,6 +24,7 @@ export class DeliveryClient {
23
24
  retry;
24
25
  sleep;
25
26
  minIntervalMs;
27
+ maxArtifactBytes;
26
28
  lastRequestAt = 0;
27
29
  constructor(opts = {}) {
28
30
  this.cfg = opts.config ?? resolveDeliveryConfig();
@@ -30,6 +32,7 @@ export class DeliveryClient {
30
32
  this.retry = { ...DEFAULT_RETRY, ...opts.retry };
31
33
  this.sleep = opts.sleep ?? defaultSleep;
32
34
  this.minIntervalMs = opts.minRequestIntervalMs ?? DEFAULT_MIN_INTERVAL_MS;
35
+ this.maxArtifactBytes = opts.maxArtifactBytes ?? MAX_ARTIFACT_BYTES;
33
36
  if (!this.cfg.baseUrl) {
34
37
  throw new DeliveryError('Delivery endpoint is not configured. Set EDITMAMEI_DELIVERY_URL ' +
35
38
  '(e.g. http://localhost:8787 for a local wrangler dev Worker).', 0, 'not_configured');
@@ -52,9 +55,55 @@ export class DeliveryClient {
52
55
  const res = await this.get(`/v1/modules/${sku}/${version}`, key);
53
56
  if (!res.ok)
54
57
  throw this.errorFor(res.status, await safeText(res), this.retryAfterMsOf(res));
55
- return new Uint8Array(await res.arrayBuffer());
58
+ const declared = Number(res.headers?.get('content-length'));
59
+ if (Number.isFinite(declared) && declared > this.maxArtifactBytes) {
60
+ throw this.oversizeError(res.status, declared);
61
+ }
62
+ const body = res.body;
63
+ if (!body) {
64
+ const buf = new Uint8Array(await res.arrayBuffer());
65
+ if (buf.length > this.maxArtifactBytes)
66
+ throw this.oversizeError(res.status, buf.length);
67
+ return buf;
68
+ }
69
+ return await this.readCapped(body, res.status);
56
70
  });
57
71
  }
72
+ async readCapped(body, status) {
73
+ const reader = body.getReader();
74
+ const chunks = [];
75
+ let total = 0;
76
+ try {
77
+ for (;;) {
78
+ const { done, value } = await reader.read();
79
+ if (done)
80
+ break;
81
+ total += value.byteLength;
82
+ if (total > this.maxArtifactBytes) {
83
+ try {
84
+ await reader.cancel('artifact exceeds byte cap');
85
+ }
86
+ catch {
87
+ }
88
+ throw this.oversizeError(status, total);
89
+ }
90
+ chunks.push(value);
91
+ }
92
+ }
93
+ finally {
94
+ reader.releaseLock();
95
+ }
96
+ const out = new Uint8Array(total);
97
+ let offset = 0;
98
+ for (const chunk of chunks) {
99
+ out.set(chunk, offset);
100
+ offset += chunk.byteLength;
101
+ }
102
+ return out;
103
+ }
104
+ oversizeError(status, sizeBytes) {
105
+ return new DeliveryError(`Artifact exceeds the ${this.maxArtifactBytes}-byte cap (${sizeBytes} bytes) — refusing to buffer further.`, status, 'oversize');
106
+ }
58
107
  async withRetry(fn) {
59
108
  let lastErr;
60
109
  for (let attempt = 1; attempt <= this.retry.attempts; attempt++) {
@@ -1,7 +1,9 @@
1
1
  import { DeliveryClient, DeliveryError } from './client.js';
2
2
  import { sha256Hex } from './crypto.js';
3
- import { verifyModuleSignature } from './signing.js';
3
+ import { verifyModuleSignature, verifyModuleSignatureV2, digestsRootSha256Hex, isModuleFileDigestArray, } from './signing.js';
4
4
  import { installModule, readInstalledModule } from './store.js';
5
+ import { Logger } from '../utils/logger.js';
6
+ const logger = new Logger('Modules');
5
7
  const SKU_RE = /^[a-z0-9-]{2,32}$/;
6
8
  const VERSION_RE = /^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/;
7
9
  const MAX_ARTIFACT_BYTES = 64 * 1024 * 1024;
@@ -99,6 +101,20 @@ export async function provisionModules(key, opts = {}) {
99
101
  });
100
102
  continue;
101
103
  }
104
+ let filesForRec;
105
+ let sigV2ForRec;
106
+ if (vEntry.files !== undefined || vEntry.sig_v2 !== undefined) {
107
+ if (isModuleFileDigestArray(vEntry.files) &&
108
+ typeof vEntry.sig_v2 === 'string' &&
109
+ verifyModuleSignatureV2(sku, latest, digest, digestsRootSha256Hex(vEntry.files), vEntry.sig_v2, opts.signingKeys)) {
110
+ filesForRec = vEntry.files;
111
+ sigV2ForRec = vEntry.sig_v2;
112
+ }
113
+ else {
114
+ logger.warn(`${sku} v${latest} manifest carried v2 fast-boot fields that failed verification — ` +
115
+ `installing via v1 trust only (boot will keep doing the full regen for this module)`);
116
+ }
117
+ }
102
118
  const contentKey = await client.fetchKey(key, sku);
103
119
  installModule({
104
120
  sku,
@@ -108,6 +124,7 @@ export async function provisionModules(key, opts = {}) {
108
124
  alg: contentKey.alg,
109
125
  content_key: contentKey.key,
110
126
  sig: sig,
127
+ ...(filesForRec && sigV2ForRec ? { files: filesForRec, sig_v2: sigV2ForRec } : {}),
111
128
  }, blob, opts);
112
129
  result.installed.push({ sku, version: latest });
113
130
  }
@@ -1,4 +1,4 @@
1
- import { createPublicKey, verify } from 'node:crypto';
1
+ import { createHash, createPublicKey, verify } from 'node:crypto';
2
2
  export const DEV_MODULE_SIGNING_PUBLIC_KEY = 'MCowBQYDK2VwAyEA0DfcGMets2SlBofK4iFzLddKZB6mJF/E3beKFpLRN2o=';
3
3
  const PROD_MODULE_SIGNING_PUBLIC_KEY = 'MCowBQYDK2VwAyEAweoGOWvtf+aukiAD0FpuECSbCdZMeFzF2XYzbFWwfwo=';
4
4
  export const MODULE_SIGNING_PUBLIC_KEYS = [PROD_MODULE_SIGNING_PUBLIC_KEY];
@@ -33,3 +33,40 @@ export function verifyModuleSignature(sku, version, sha256Hex, sigB64, pubKeys =
33
33
  }
34
34
  return false;
35
35
  }
36
+ export function isModuleFileDigestArray(v) {
37
+ return (Array.isArray(v) &&
38
+ v.every((e) => typeof e === 'object' &&
39
+ e !== null &&
40
+ typeof e.path === 'string' &&
41
+ typeof e.sha256 === 'string'));
42
+ }
43
+ export function canonicalDigestListString(files) {
44
+ const sorted = [...files].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
45
+ return JSON.stringify(sorted.map((f) => ({ path: f.path, sha256: f.sha256 })));
46
+ }
47
+ export function digestsRootSha256Hex(files) {
48
+ return createHash('sha256').update(canonicalDigestListString(files), 'utf8').digest('hex');
49
+ }
50
+ export function moduleSigV2Message(sku, version, artifactSha256Hex, digestsRootHex) {
51
+ return Buffer.from(`editmamei-module-sig-v2\n${sku}\n${version}\n${artifactSha256Hex}\n${digestsRootHex}`, 'utf8');
52
+ }
53
+ export function verifyModuleSignatureV2(sku, version, artifactSha256Hex, digestsRootHex, sigB64, pubKeys = MODULE_SIGNING_PUBLIC_KEYS) {
54
+ if (!sigB64)
55
+ return false;
56
+ const sig = Buffer.from(sigB64, 'base64');
57
+ if (sig.length === 0)
58
+ return false;
59
+ const msg = moduleSigV2Message(sku, version, artifactSha256Hex, digestsRootHex);
60
+ for (const b64 of pubKeys) {
61
+ const key = importSpki(b64);
62
+ if (!key)
63
+ continue;
64
+ try {
65
+ if (verify(null, msg, key, sig))
66
+ return true;
67
+ }
68
+ catch {
69
+ }
70
+ }
71
+ return false;
72
+ }