zorya-classifier 0.2.0 → 0.2.2

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 (140) hide show
  1. package/README.md +24 -8
  2. package/dist/app/classifier-config.d.ts +30 -0
  3. package/dist/app/classifier-config.js +46 -0
  4. package/dist/app/classifier-contracts.d.ts +32 -0
  5. package/dist/app/classifier-contracts.js +1 -0
  6. package/dist/app/classifier-representation.d.ts +5 -0
  7. package/dist/app/classifier-representation.js +33 -0
  8. package/dist/app/classifier-runtime.d.ts +7 -0
  9. package/dist/app/classifier-runtime.js +71 -0
  10. package/dist/app/classifier-spatial.d.ts +31 -0
  11. package/dist/app/classifier-spatial.js +78 -0
  12. package/dist/app/cli-arguments.d.ts +2 -2
  13. package/dist/app/create-classifier.d.ts +4 -29
  14. package/dist/app/create-classifier.js +37 -237
  15. package/dist/cli.js +1 -1
  16. package/dist/entities/classification.d.ts +98 -0
  17. package/dist/entities/classification.js +28 -0
  18. package/dist/entities/contracts.d.ts +6 -471
  19. package/dist/entities/contracts.js +6 -97
  20. package/dist/entities/decision.d.ts +211 -0
  21. package/dist/entities/decision.js +33 -0
  22. package/dist/entities/geometry.d.ts +37 -0
  23. package/dist/entities/geometry.js +26 -0
  24. package/dist/entities/image.d.ts +39 -0
  25. package/dist/entities/image.js +15 -0
  26. package/dist/entities/localization.d.ts +125 -0
  27. package/dist/entities/localization.js +13 -0
  28. package/dist/entities/object-proposals.d.ts +4 -1
  29. package/dist/entities/segmentation-metadata.d.ts +70 -0
  30. package/dist/entities/segmentation-metadata.js +21 -1
  31. package/dist/entities/segmentation-verification.d.ts +1 -0
  32. package/dist/entities/segmentation.d.ts +6 -1
  33. package/dist/entities/validation.d.ts +2 -0
  34. package/dist/entities/validation.js +9 -0
  35. package/dist/entities/whole-object.d.ts +4 -0
  36. package/dist/features/choice-beam-layout.js +2 -7
  37. package/dist/features/proposals/presentation.d.ts +21 -0
  38. package/dist/features/proposals/presentation.js +122 -0
  39. package/dist/features/proposals/validation.d.ts +138 -0
  40. package/dist/features/proposals/validation.js +125 -0
  41. package/dist/features/segmentation/box-check.js +10 -23
  42. package/dist/features/segmentation/mask.js +2 -7
  43. package/dist/features/segmentation/region-result.d.ts +18 -0
  44. package/dist/features/segmentation/region-result.js +171 -0
  45. package/dist/features/segmentation/source-mask.d.ts +6 -0
  46. package/dist/features/segmentation/source-mask.js +32 -0
  47. package/dist/features/segmentation/validation.d.ts +9 -0
  48. package/dist/features/segmentation/validation.js +94 -0
  49. package/dist/infrastructure/decision-transport/errors.d.ts +8 -0
  50. package/dist/infrastructure/decision-transport/errors.js +34 -0
  51. package/dist/infrastructure/decision-transport/images.d.ts +1 -0
  52. package/dist/infrastructure/decision-transport/images.js +52 -0
  53. package/dist/infrastructure/{openrouter-common.d.ts → decision-transport/request.d.ts} +6 -15
  54. package/dist/infrastructure/decision-transport/request.js +162 -0
  55. package/dist/infrastructure/decision-transport/response.d.ts +1 -0
  56. package/dist/infrastructure/decision-transport/response.js +72 -0
  57. package/dist/infrastructure/decision-transport/route-identity.d.ts +11 -0
  58. package/dist/infrastructure/decision-transport/route-identity.js +23 -0
  59. package/dist/infrastructure/openrouter-vision.js +1 -1
  60. package/dist/infrastructure/openrouter.js +7 -19
  61. package/dist/infrastructure/raster.js +3 -8
  62. package/dist/infrastructure/segmentation/grabcut/index.d.ts +5 -1
  63. package/dist/infrastructure/segmentation/grabcut/index.js +6 -5
  64. package/dist/infrastructure/segmentation/grabcut/masks.d.ts +49 -0
  65. package/dist/infrastructure/segmentation/grabcut/masks.js +89 -0
  66. package/dist/infrastructure/segmentation/grabcut/model-asset.d.ts +4 -0
  67. package/dist/infrastructure/segmentation/grabcut/model-asset.js +4 -0
  68. package/dist/infrastructure/segmentation/grabcut/runtime.d.ts +70 -0
  69. package/dist/infrastructure/segmentation/grabcut/runtime.js +96 -0
  70. package/dist/infrastructure/segmentation/grabcut/worker-inference.d.ts +4 -43
  71. package/dist/infrastructure/segmentation/grabcut/worker-inference.js +4 -187
  72. package/dist/infrastructure/segmentation/mobile-sam/index.d.ts +3 -58
  73. package/dist/infrastructure/segmentation/mobile-sam/index.js +2 -472
  74. package/dist/infrastructure/segmentation/mobile-sam/input.d.ts +46 -0
  75. package/dist/infrastructure/segmentation/mobile-sam/input.js +83 -0
  76. package/dist/infrastructure/segmentation/mobile-sam/model-assets.d.ts +8 -0
  77. package/dist/infrastructure/segmentation/mobile-sam/model-assets.js +8 -0
  78. package/dist/infrastructure/segmentation/mobile-sam/object-proposals.d.ts +7 -0
  79. package/dist/infrastructure/segmentation/mobile-sam/object-proposals.js +124 -0
  80. package/dist/infrastructure/segmentation/mobile-sam/options.d.ts +43 -0
  81. package/dist/infrastructure/segmentation/mobile-sam/options.js +19 -0
  82. package/dist/infrastructure/segmentation/mobile-sam/proposal-masks.d.ts +26 -0
  83. package/dist/infrastructure/segmentation/mobile-sam/proposal-masks.js +71 -0
  84. package/dist/infrastructure/segmentation/mobile-sam/segmentation-masks.d.ts +112 -0
  85. package/dist/infrastructure/segmentation/mobile-sam/segmentation-masks.js +230 -0
  86. package/dist/infrastructure/segmentation/mobile-sam/segmenter.d.ts +22 -0
  87. package/dist/infrastructure/segmentation/mobile-sam/segmenter.js +268 -0
  88. package/dist/infrastructure/segmentation/mobile-sam/worker-expand.d.ts +7 -0
  89. package/dist/infrastructure/segmentation/mobile-sam/worker-expand.js +188 -0
  90. package/dist/infrastructure/segmentation/mobile-sam/worker-inference.d.ts +6 -149
  91. package/dist/infrastructure/segmentation/mobile-sam/worker-inference.js +6 -845
  92. package/dist/infrastructure/segmentation/mobile-sam/worker-models.d.ts +14 -0
  93. package/dist/infrastructure/segmentation/mobile-sam/worker-models.js +72 -0
  94. package/dist/infrastructure/segmentation/mobile-sam/worker-proposals.d.ts +7 -0
  95. package/dist/infrastructure/segmentation/mobile-sam/worker-proposals.js +159 -0
  96. package/dist/infrastructure/segmentation/mobile-sam/worker-segment.d.ts +4 -0
  97. package/dist/infrastructure/segmentation/mobile-sam/worker-segment.js +126 -0
  98. package/dist/infrastructure/segmentation/native-protocol.d.ts +59 -34
  99. package/dist/infrastructure/segmentation/native-protocol.js +26 -16
  100. package/dist/infrastructure/segmentation/proposal-presentation-input.d.ts +20 -0
  101. package/dist/infrastructure/segmentation/proposal-presentation-input.js +107 -0
  102. package/dist/infrastructure/segmentation/proposal-presentation-pixels.d.ts +8 -0
  103. package/dist/infrastructure/segmentation/proposal-presentation-pixels.js +93 -0
  104. package/dist/infrastructure/segmentation/proposal-presentation.js +10 -201
  105. package/dist/infrastructure/vision-chat/options.d.ts +62 -0
  106. package/dist/infrastructure/vision-chat/options.js +46 -0
  107. package/dist/infrastructure/vision-chat/request.d.ts +23 -0
  108. package/dist/infrastructure/vision-chat/request.js +109 -0
  109. package/dist/infrastructure/vision-chat/response.d.ts +3 -0
  110. package/dist/infrastructure/vision-chat/response.js +105 -0
  111. package/dist/infrastructure/vision-chat.d.ts +4 -61
  112. package/dist/infrastructure/vision-chat.js +8 -271
  113. package/dist/openai-compatible.js +1 -1
  114. package/dist/processes/extract-from-region.js +11 -216
  115. package/dist/processes/extract.d.ts +2 -8
  116. package/dist/processes/extract.js +12 -128
  117. package/dist/processes/proposal-location.js +5 -251
  118. package/docs/0.2.0-plan.md +3 -3
  119. package/docs/README.ru.md +42 -23
  120. package/docs/acceptance.md +5 -5
  121. package/docs/agents.ru.md +95 -0
  122. package/docs/api.md +4 -2
  123. package/docs/architecture.md +33 -5
  124. package/docs/architecture.ru.md +146 -0
  125. package/docs/benchmarks.md +4 -2
  126. package/docs/development.ru.md +141 -0
  127. package/docs/operations.md +4 -4
  128. package/docs/provenance.json +5 -1
  129. package/docs/publishing.md +8 -0
  130. package/docs/refactoring-plan.ru.md +183 -0
  131. package/docs/v02-usage.md +8 -6
  132. package/docs/vision-results.md +2 -0
  133. package/package.json +5 -3
  134. package/dist/infrastructure/boundary-view.d.ts +0 -2
  135. package/dist/infrastructure/boundary-view.js +0 -263
  136. package/dist/infrastructure/openrouter-common.js +0 -317
  137. package/dist/infrastructure/text-representation.d.ts +0 -23
  138. package/dist/infrastructure/text-representation.js +0 -226
  139. package/docs/evidence/v02/categorical-heldout-v4/README.md +0 -35
  140. package/docs/evidence/v02/proposal-resource-soak-261dc23.md +0 -15
package/README.md CHANGED
@@ -2,11 +2,11 @@
2
2
 
3
3
  [![npm version](https://img.shields.io/npm/v/zorya-classifier)](https://www.npmjs.com/package/zorya-classifier)
4
4
 
5
- Provider-independent text/image classification and coarse-to-fine object localization for Node.js and TypeScript. MIT application code. The library never selects or connects a model for you: create a client with an explicit `DecisionPort`, either injected by your application or built with an adapter you configure. The model and provider shown in examples are examples, not defaults. Ordinary vision language models and native decision APIs are both supported.
5
+ Provider-independent text/image classification for Node.js and TypeScript, with experimental, unqualified spatial localization and object extraction. MIT application code. The library never selects or connects a model for you: create a client with an explicit `DecisionPort`, either injected by your application or built with an adapter you configure. The model and provider shown in examples are examples, not defaults. Ordinary vision language models and native decision APIs are both supported for closed classification.
6
6
 
7
7
  Use an explicitly configured image-capable model through a supported adapter, or implement the small `DecisionPort` for another protocol. OpenRouter is an optional adapter, not a mandatory service. A more capable model may help on a task, but model strength does not guarantee a monotonic accuracy improvement. Compatibility and quality vary; see the exact [tested models/results](docs/vision-results.md), [acceptance](docs/acceptance.md), and historical [Jev baseline](docs/results.md).
8
8
 
9
- [Русское руководство](docs/README.ru.md) · [API](docs/api.md) · [Architecture](docs/architecture.md) · [Benchmarks](docs/benchmarks.md)
9
+ [Русское руководство](docs/README.ru.md) · [API](docs/api.md) · [Architecture](docs/architecture.md) · [Архитектура (RU)](docs/architecture.ru.md) · [Разработка (RU)](docs/development.ru.md) · [Benchmarks](docs/benchmarks.md)
10
10
 
11
11
  Version 0.2 adds region-seeded segmentation, mask-derived bounds and optional transparent cutouts, with a closed completeness check and one bounded mask expansion. See the [usage guide](docs/v02-usage.md) for contracts, backend ownership and CLI.
12
12
 
@@ -22,7 +22,23 @@ Node.js 22.12+ is required. Source: [zoomplus/zorya-classifier](https://github.c
22
22
  npm install zorya-classifier
23
23
  ```
24
24
 
25
- The release archive also installs with `npm install ./zorya-classifier-0.1.0.tgz`. Runtime dependencies are Zod and Sharp; model weights, Electron, a database and background services are not included. Optional local segmentation backends and their model assets are a separate responsibility of the caller; the library does not download or choose them.
25
+ The release archive also installs with `npm install ./zorya-classifier-0.2.0.tgz` (filename follows `package.json` version; not a claim of a newly published release). Runtime dependencies are Zod and Sharp; model weights, Electron, a database and background services are not included. Optional local segmentation backends and their model assets are a separate responsibility of the caller; the library does not download or choose them.
26
+
27
+ ## Capability and status
28
+
29
+ Further accuracy experiments on spatial workflows are stopped; no localization, extraction, or proposal strategy is promoted for general use. Historical metrics below and in `docs/evidence/**` are preserved as recorded.
30
+
31
+ | Capability | Status | Notes |
32
+ | --------------------------------------------------------------- | ------------ | --------------------------------------------------------------------- |
33
+ | `classify` with an explicit `DecisionPort` / supported adapters | Supported | Closed class ID; no universal model accuracy claim |
34
+ | Default `locate` (region grid search) | Experimental | Hypothesized grid cell, not whole-object geometry or proof of absence |
35
+ | `RefinementPort` | Experimental | No general quality qualification |
36
+ | `locate({ mode: 'whole-object' })` | Experimental | Interval or segmentation paths; unqualified |
37
+ | `extract`, `SegmentationPort`, box-check composition | Experimental | Structural checks ≠ semantic object or mask quality |
38
+ | `objectProposals` / native segmentation factories | Experimental | Caller-owned; unqualified |
39
+ | `representation: { type: 'experimental-text', … }` | Rejected | `UNSUPPORTED` until a profile qualifies |
40
+
41
+ Heldout region-seeded metrics (one documented recipe, not universal): 26/60 positive coarse seed hits; 8/60 complete whole-object boxes; 0 false seeds on 20 negatives. Among 30 exact-canvas masks: 8 reached IoU 0.8, 3 failed, 19 had no predicted mask. H8 DEV reported 7/9 positives with 2/3 false outputs and did not qualify. A narrow historical admission pass is not broad spatial qualification.
26
42
 
27
43
  ## Example: Luna Decisions
28
44
 
@@ -101,9 +117,9 @@ try {
101
117
 
102
118
  Supply the **full trusted chat-completions URL**, such as your local `http://localhost:8000/v1/chat/completions`, and the actual deployed model ID. Anonymous local servers can omit the key; custom headers support other authentication. These are integration examples, not a claim that every provider/model has been live-qualified. Other wire protocols can implement the exported `DecisionPort`. Keep keys on a trusted server, outside frontend bundles and Git.
103
119
 
104
- ## Locate an object
120
+ ## Locate an object (experimental)
105
121
 
106
- With either configured client:
122
+ Default region `locate` is experimental and unqualified. With either configured client:
107
123
 
108
124
  ```ts
109
125
  const result = await client.locate({
@@ -117,9 +133,9 @@ if (result.status === 'located') console.log(result.region)
117
133
 
118
134
  The locator uses up to three sequential calls: coarse 4×4 regions, fine grids in four padded regions, then four enlarged candidates. Coordinates come from code, never free-form model coordinates. Ordinary-model rankings select candidates; independent present/absent/unknown answers govern abstention. Multiple matching physical instances are allowed; one candidate is returned. Localization requires the model/endpoint to accept multiple images per call (up to nine); single-image-only endpoints can still support `classify`.
119
135
 
120
- ## Extract a mask-derived object
136
+ ## Extract a mask-derived object (experimental)
121
137
 
122
- For a visible object box, center, or transparent cutout, use `extract` with an explicitly configured caller-owned segmenter. The existing region locator supplies a seed; the segmenter receives that seed while processing the full oriented source image. The library derives the returned box and center from actual mask pixels. After segmentation, the caller's decision port checks the original image with the mask-derived box and seed anchor. An incomplete box permits one enclosing-mask correction and one recheck; unresolved results remain unknown. This adds one or two closed checks to the normal region requests, without model-generated coordinates or an extent search. See the [0.2 usage guide](docs/v02-usage.md) and runnable [`extract-object.ts`](examples/extract-object.ts). The classifier and segmenter are separately caller-owned and both must be disposed.
138
+ Extraction and caller-owned segmentation are experimental and unqualified. For a visible object box, center, or transparent cutout, use `extract` with an explicitly configured caller-owned segmenter. The existing region locator supplies a seed; the segmenter receives that seed while processing the full oriented source image. The library derives the returned box and center from actual mask pixels only. After segmentation, the caller's decision port checks the full source with the mask-derived box and original seed anchor: `complete` yields the result (optional cutout); `needs-expansion` allows at most one enclosing-mask expansion and one final check (a final `complete` can still produce the result); unresolved checks, missing expansion support, no valid enclosing mask, or a failed final check yield `unknown` with no second expansion. Crops, resize and padding preserve source/mask alignment; box-check rendering uses injected `RasterPort.imageState` on the full canvas. This adds one or two closed checks to the normal region requests, without model-generated coordinates or an extent search. See the [0.2 usage guide](docs/v02-usage.md) and runnable [`extract-object.ts`](https://github.com/zoomplus/zorya-classifier/blob/main/examples/extract-object.ts). The classifier and segmenter are separately caller-owned and both must be disposed.
123
139
 
124
140
  ## Development and limits
125
141
 
@@ -137,4 +153,4 @@ Tests are offline. Examples, CLI and explicitly authorized model benchmarks make
137
153
 
138
154
  A model must understand the input, follow instructions and produce the checked answer shape. JSON Schema/JSON-object modes are opt-in when the chosen endpoint supports them; prompt-only mode does not require structured-output support. No universal accuracy, calibration or sub-second guarantee is asserted. Legacy region refinement uses `RefinementPort`; the 0.2 explicit `extract` workflow uses a caller-owned `SegmentationPort`.
139
155
 
140
- See [CONTRIBUTING](CONTRIBUTING.md), [SECURITY](SECURITY.md), [NOTICE](NOTICE.md), and [LICENSE](LICENSE).
156
+ See [CONTRIBUTING](https://github.com/zoomplus/zorya-classifier/blob/main/CONTRIBUTING.md), [SECURITY](https://github.com/zoomplus/zorya-classifier/blob/main/SECURITY.md), [NOTICE](NOTICE.md), and [LICENSE](LICENSE).
@@ -0,0 +1,30 @@
1
+ import { z } from 'zod';
2
+ import type { ObjectProposalPort } from '../entities/object-proposals.js';
3
+ import type { SegmentationPort } from '../entities/segmentation.js';
4
+ import type { ClassifierOptions } from './classifier-contracts.js';
5
+ declare const configSchema: z.ZodObject<{
6
+ timeoutMs: z.ZodDefault<z.ZodNumber>;
7
+ concurrency: z.ZodDefault<z.ZodNumber>;
8
+ maxQueue: z.ZodDefault<z.ZodNumber>;
9
+ maxInputBytes: z.ZodDefault<z.ZodNumber>;
10
+ }, "strip", z.ZodTypeAny, {
11
+ timeoutMs: number;
12
+ concurrency: number;
13
+ maxQueue: number;
14
+ maxInputBytes: number;
15
+ }, {
16
+ timeoutMs?: number | undefined;
17
+ concurrency?: number | undefined;
18
+ maxQueue?: number | undefined;
19
+ maxInputBytes?: number | undefined;
20
+ }>;
21
+ export type ClassifierRuntimeConfig = z.infer<typeof configSchema>;
22
+ type ValidatedClassifierPorts = {
23
+ segmenter: SegmentationPort | undefined;
24
+ objectProposals: ObjectProposalPort | undefined;
25
+ };
26
+ export declare function validateClassifierOptions(options: ClassifierOptions): {
27
+ config: ClassifierRuntimeConfig;
28
+ ports: ValidatedClassifierPorts;
29
+ };
30
+ export {};
@@ -0,0 +1,46 @@
1
+ import { z } from 'zod';
2
+ import { parse } from '../entities/contracts.js';
3
+ import { ClassifierError } from '../entities/errors.js';
4
+ const configSchema = z.object({
5
+ timeoutMs: z.number().int().min(1).max(120000).default(45000),
6
+ concurrency: z.number().int().min(1).max(4).default(2),
7
+ maxQueue: z.number().int().min(0).max(32).default(16),
8
+ maxInputBytes: z
9
+ .number()
10
+ .int()
11
+ .min(1)
12
+ .max(256 * 1024 * 1024)
13
+ .default(64 * 1024 * 1024),
14
+ });
15
+ export function validateClassifierOptions(options) {
16
+ if (!options || typeof options.decision?.decide !== 'function')
17
+ throw new ClassifierError('INVALID_INPUT', 'A DecisionPort is required');
18
+ const segmenter = options.segmentation;
19
+ const objectProposals = options.objectProposals;
20
+ if (segmenter !== undefined &&
21
+ (!segmenter ||
22
+ typeof segmenter.segment !== 'function' ||
23
+ (segmenter.expand !== undefined && typeof segmenter.expand !== 'function') ||
24
+ typeof segmenter.settle !== 'function' ||
25
+ typeof segmenter.dispose !== 'function'))
26
+ throw new ClassifierError('INVALID_INPUT', 'segmentation must implement SegmentationPort');
27
+ if (options.segmentationBoxCheck !== undefined &&
28
+ (!options.segmentationBoxCheck || typeof options.segmentationBoxCheck.check !== 'function'))
29
+ throw new ClassifierError('INVALID_INPUT', 'segmentationBoxCheck must implement its check port');
30
+ if (objectProposals !== undefined &&
31
+ (!objectProposals ||
32
+ typeof objectProposals.propose !== 'function' ||
33
+ typeof objectProposals.settle !== 'function' ||
34
+ typeof objectProposals.dispose !== 'function'))
35
+ throw new ClassifierError('INVALID_INPUT', 'objectProposals must implement ObjectProposalPort');
36
+ const config = parse(configSchema, {
37
+ timeoutMs: options.timeoutMs,
38
+ concurrency: options.concurrency,
39
+ maxQueue: options.maxQueue,
40
+ maxInputBytes: options.maxInputBytes,
41
+ });
42
+ return {
43
+ config,
44
+ ports: { segmenter, objectProposals },
45
+ };
46
+ }
@@ -0,0 +1,32 @@
1
+ import type { ClassificationResult, ClassifyInput, DecisionPort, LocalizationResult, LocateInput, RefinementPort } from '../entities/contracts.js';
2
+ import type { ExtractInput, ExtractionResult, SegmentationPort } from '../entities/segmentation.js';
3
+ import type { ObjectProposalPort } from '../entities/object-proposals.js';
4
+ import type { SegmentationBoxCheckPort } from '../entities/segmentation-verification.js';
5
+ import type { AnyLocateInput, WholeObjectLocateInput, WholeObjectLocalizationResult } from '../entities/whole-object.js';
6
+ export interface ClassifierOptions {
7
+ decision: DecisionPort;
8
+ timeoutMs?: number;
9
+ concurrency?: number;
10
+ maxQueue?: number;
11
+ maxInputBytes?: number;
12
+ /** @experimental Optional legacy region refinement; unqualified for general use. */
13
+ refinement?: RefinementPort;
14
+ /** Caller-owned; classifier disposal never disposes a shared segmenter. @experimental Unqualified segmentation adapter. */
15
+ segmentation?: SegmentationPort;
16
+ /** Optional caller-owned containment checker; by default reuses the injected decision port. @experimental Unqualified box-check override. */
17
+ segmentationBoxCheck?: SegmentationBoxCheckPort;
18
+ /** Explicit, caller-owned pixel-mask proposal strategy for whole-object operations. @experimental Unqualified proposal path. */
19
+ objectProposals?: ObjectProposalPort;
20
+ }
21
+ export interface Classifier {
22
+ classify(input: ClassifyInput): Promise<ClassificationResult>;
23
+ /** @experimental Unqualified spatial localization; see {@link LocateInput} and {@link WholeObjectLocateInput}. */
24
+ locate(input: WholeObjectLocateInput): Promise<WholeObjectLocalizationResult>;
25
+ /** @experimental Unqualified coarse region search; returns a hypothesized grid cell. */
26
+ locate(input: LocateInput): Promise<LocalizationResult>;
27
+ /** @experimental Unqualified spatial localization. */
28
+ locate(input: AnyLocateInput): Promise<LocalizationResult | WholeObjectLocalizationResult>;
29
+ /** @experimental Region-seeded extraction; unqualified for general mask or object accuracy. */
30
+ extract(input: ExtractInput): Promise<ExtractionResult>;
31
+ dispose(): Promise<void>;
32
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,5 @@
1
+ import type { Representation } from '../entities/contracts.js';
2
+ import type { ImageRepresentationPort } from '../entities/representation.js';
3
+ export declare function createClassifierRepresentation(experimental: ImageRepresentationPort | undefined): {
4
+ representationFor(value: Representation | undefined): ImageRepresentationPort | undefined;
5
+ };
@@ -0,0 +1,33 @@
1
+ import { ClassifierError } from '../entities/errors.js';
2
+ import { preparedTextSchema, representationLimits } from '../entities/representation.js';
3
+ import { parse } from '../entities/contracts.js';
4
+ export function createClassifierRepresentation(experimental) {
5
+ const textRepresentation = experimental
6
+ ? {
7
+ async prepare(input) {
8
+ const result = parse(preparedTextSchema, await experimental.prepare(input), 'INVALID_RESPONSE');
9
+ const bytes = result.state.reduce((sum, part) => sum + Buffer.byteLength(part, 'utf8'), 0);
10
+ if (bytes > representationLimits.totalBytes || bytes !== result.metadata.bytes)
11
+ throw new ClassifierError('INVALID_RESPONSE', 'Representation byte accounting is inconsistent');
12
+ return {
13
+ state: result.state,
14
+ metadata: {
15
+ ...result.metadata,
16
+ views: result.metadata.views.map(({ content, ...view }) => ({
17
+ ...view,
18
+ ...(content === undefined ? {} : { content }),
19
+ })),
20
+ },
21
+ };
22
+ },
23
+ }
24
+ : undefined;
25
+ function representationFor(value) {
26
+ if (value?.type !== 'experimental-text')
27
+ return undefined;
28
+ if (!textRepresentation)
29
+ throw new ClassifierError('UNSUPPORTED', 'No text-image profile has passed release qualification yet');
30
+ return textRepresentation;
31
+ }
32
+ return { representationFor };
33
+ }
@@ -0,0 +1,7 @@
1
+ import type { ClassifierRuntimeConfig } from './classifier-config.js';
2
+ export declare function parseOperationSignal(value: unknown): AbortSignal | undefined;
3
+ export declare function createClassifierRuntime(config: ClassifierRuntimeConfig): {
4
+ dispose: () => Promise<void>;
5
+ assertAcceptingOperations: () => void;
6
+ withOwnedInput: <TSnapshot, TResult>(byteCount: number, parentSignal: AbortSignal | undefined, snapshotFactory: () => TSnapshot, task: (snapshot: TSnapshot, signal: AbortSignal) => Promise<TResult>) => Promise<TResult>;
7
+ };
@@ -0,0 +1,71 @@
1
+ import { ClassifierError } from '../entities/errors.js';
2
+ import { OperationGate } from '../shared/gate.js';
3
+ import { OperationScope } from '../shared/scope.js';
4
+ import { InputBudget } from '../shared/input-budget.js';
5
+ export function parseOperationSignal(value) {
6
+ if (value === undefined)
7
+ return undefined;
8
+ if (!(value instanceof AbortSignal))
9
+ throw new ClassifierError('INVALID_INPUT', 'signal must be an AbortSignal');
10
+ return value;
11
+ }
12
+ export function createClassifierRuntime(config) {
13
+ const gate = new OperationGate(config.concurrency, config.maxQueue);
14
+ const inputBudget = new InputBudget(config.maxInputBytes);
15
+ const owned = new Map();
16
+ let disposed = false;
17
+ async function run(signal, task) {
18
+ if (disposed)
19
+ throw new ClassifierError('DISPOSED', 'Classifier has been disposed');
20
+ const scope = new OperationScope(config.timeoutMs, signal);
21
+ const job = (async () => {
22
+ let acquired = false;
23
+ try {
24
+ await gate.acquire(scope.signal);
25
+ acquired = true;
26
+ scope.guard();
27
+ const result = await task(scope.signal);
28
+ scope.guard();
29
+ return result;
30
+ }
31
+ catch (error) {
32
+ scope.guard();
33
+ throw error;
34
+ }
35
+ finally {
36
+ if (acquired)
37
+ gate.release();
38
+ scope.dispose();
39
+ owned.delete(scope);
40
+ }
41
+ })();
42
+ owned.set(scope, job);
43
+ return job;
44
+ }
45
+ async function dispose() {
46
+ disposed = true;
47
+ for (const scope of owned.keys())
48
+ scope.abort();
49
+ await Promise.allSettled(owned.values());
50
+ }
51
+ function assertAcceptingOperations() {
52
+ if (disposed)
53
+ throw new ClassifierError('DISPOSED', 'Classifier has been disposed');
54
+ gate.assertAvailable();
55
+ }
56
+ async function withOwnedInput(byteCount, parentSignal, snapshotFactory, task) {
57
+ const release = inputBudget.reserve(byteCount);
58
+ try {
59
+ const snapshot = snapshotFactory();
60
+ return await run(parentSignal, (signal) => task(snapshot, signal));
61
+ }
62
+ finally {
63
+ release();
64
+ }
65
+ }
66
+ return {
67
+ dispose,
68
+ assertAcceptingOperations,
69
+ withOwnedInput,
70
+ };
71
+ }
@@ -0,0 +1,31 @@
1
+ import type { DecisionPort, RasterPort } from '../entities/contracts.js';
2
+ import type { CutoutRasterPort } from '../entities/cutout-raster.js';
3
+ import type { BoundaryViewPort } from '../entities/boundary-view.js';
4
+ import type { ObjectProposalPort, ObjectProposalPresentationPort } from '../entities/object-proposals.js';
5
+ import type { ImageRepresentationPort } from '../entities/representation.js';
6
+ import type { ExtractInput, ExtractionResult, SegmentationPort } from '../entities/segmentation.js';
7
+ import type { SegmentationBoxCheckPort } from '../entities/segmentation-verification.js';
8
+ import type { WholeObjectLocateInput, WholeObjectLocalizationResult } from '../entities/whole-object.js';
9
+ import type { WholeObjectIntervalPolicy } from '../processes/whole-object.js';
10
+ type ClassifierSpatialDeps = {
11
+ getDecision: () => DecisionPort;
12
+ raster: RasterPort;
13
+ cutoutRaster: CutoutRasterPort;
14
+ segmenter: SegmentationPort | undefined;
15
+ boxCheck: SegmentationBoxCheckPort | undefined;
16
+ proposalDependencies: {
17
+ decision: DecisionPort;
18
+ raster: RasterPort;
19
+ image: CutoutRasterPort;
20
+ proposals: ObjectProposalPort;
21
+ presentation: ObjectProposalPresentationPort;
22
+ } | undefined;
23
+ boundaryView: BoundaryViewPort | undefined;
24
+ intervalPolicy: WholeObjectIntervalPolicy | undefined;
25
+ };
26
+ export declare function createClassifierSpatial(deps: ClassifierSpatialDeps): {
27
+ locateWhole: (input: Omit<WholeObjectLocateInput, "signal">, signal: AbortSignal, representation: ImageRepresentationPort | undefined) => Promise<WholeObjectLocalizationResult>;
28
+ extractRegion: (input: Omit<ExtractInput, "signal">, signal: AbortSignal, representation: ImageRepresentationPort | undefined) => Promise<ExtractionResult>;
29
+ extractWithProposals: (snapshot: Omit<ExtractInput, "signal">, signal: AbortSignal, representation: ImageRepresentationPort | undefined) => Promise<ExtractionResult>;
30
+ };
31
+ export {};
@@ -0,0 +1,78 @@
1
+ import { ClassifierError } from '../entities/errors.js';
2
+ import { locateWholeObjectInput } from '../processes/whole-object.js';
3
+ import { locateInput } from '../processes/locate.js';
4
+ import { extractFromRegion } from '../processes/extract-from-region.js';
5
+ import { extractObject } from '../processes/extract.js';
6
+ import { locateFromProposals } from '../processes/proposal-location.js';
7
+ export function createClassifierSpatial(deps) {
8
+ const { getDecision, raster, cutoutRaster, segmenter, boxCheck, proposalDependencies, boundaryView, intervalPolicy, } = deps;
9
+ function extractRegion(input, signal, representation) {
10
+ if (!segmenter || !boxCheck)
11
+ throw new ClassifierError('UNSUPPORTED', 'Region extraction requires a SegmentationPort');
12
+ if (representation)
13
+ throw new ClassifierError('UNSUPPORTED', 'Checked segmentation requires vision input');
14
+ return extractFromRegion({ ...input, signal }, {
15
+ raster,
16
+ image: cutoutRaster,
17
+ segmenter,
18
+ boxCheck,
19
+ locateRegion: (source, { signal: operationSignal, ...request }) => locateInput({ ...request, image: source.bytes }, getDecision(), raster, operationSignal, undefined, representation),
20
+ });
21
+ }
22
+ async function locateWhole(input, signal, representation) {
23
+ if (segmenter) {
24
+ const result = await extractRegion(input, signal, representation);
25
+ if (result.status === 'extracted')
26
+ return result.location;
27
+ if (result.status === 'unknown' && result.reason === 'segmentation-uncertain')
28
+ return {
29
+ status: 'unknown',
30
+ reason: 'segmentation-uncertain',
31
+ metadata: 'metadata' in result ? result.metadata : result.location.metadata,
32
+ ...(result.verification ? { verification: result.verification } : {}),
33
+ };
34
+ return result;
35
+ }
36
+ if (proposalDependencies) {
37
+ if (representation)
38
+ throw new ClassifierError('UNSUPPORTED', 'Mask proposal selection requires vision input');
39
+ return (await locateFromProposals(input, proposalDependencies, signal)).location;
40
+ }
41
+ return locateWholeObjectInput(input, getDecision(), raster, signal, representation, boundaryView, intervalPolicy);
42
+ }
43
+ function extractWithProposals(snapshot, signal, representation) {
44
+ let prepared;
45
+ const selectedMask = {
46
+ async segment() {
47
+ if (!prepared?.mask || !prepared.segmentation)
48
+ throw new ClassifierError('INVALID_RESPONSE', 'Proposal selection omitted its mask');
49
+ return {
50
+ status: 'segmented',
51
+ mask: prepared.mask,
52
+ metadata: prepared.segmentation,
53
+ };
54
+ },
55
+ async settle() { },
56
+ async dispose() { },
57
+ };
58
+ return extractObject({ ...snapshot, mode: 'whole-object', signal }, {
59
+ raster,
60
+ image: cutoutRaster,
61
+ segmenter: selectedMask,
62
+ locateWhole: async (source, { signal: requestSignal, ...request }) => {
63
+ const wholeInput = {
64
+ ...request,
65
+ mode: 'whole-object',
66
+ image: source.bytes,
67
+ };
68
+ if (!proposalDependencies)
69
+ throw new ClassifierError('UNSUPPORTED', 'ObjectProposalPort is required');
70
+ if (representation)
71
+ throw new ClassifierError('UNSUPPORTED', 'Mask proposal selection requires vision input');
72
+ prepared = await locateFromProposals(wholeInput, proposalDependencies, requestSignal);
73
+ return prepared.location;
74
+ },
75
+ });
76
+ }
77
+ return { locateWhole, extractRegion, extractWithProposals };
78
+ }
@@ -14,8 +14,8 @@ declare const schema: z.ZodObject<{
14
14
  value: string;
15
15
  target: string;
16
16
  command: "classify-text" | "classify-image" | "locate" | "extract";
17
- mode?: "region" | "whole-object" | undefined;
18
17
  provider?: "cpu" | "dml" | undefined;
18
+ mode?: "region" | "whole-object" | undefined;
19
19
  output?: string | undefined;
20
20
  backend?: "mobile-sam" | "grabcut" | undefined;
21
21
  encoder?: string | undefined;
@@ -25,8 +25,8 @@ declare const schema: z.ZodObject<{
25
25
  value: string;
26
26
  target: string;
27
27
  command: "classify-text" | "classify-image" | "locate" | "extract";
28
- mode?: "region" | "whole-object" | undefined;
29
28
  provider?: "cpu" | "dml" | undefined;
29
+ mode?: "region" | "whole-object" | undefined;
30
30
  output?: string | undefined;
31
31
  backend?: "mobile-sam" | "grabcut" | undefined;
32
32
  encoder?: string | undefined;
@@ -1,33 +1,8 @@
1
- import type { ClassificationResult, ClassifyInput, DecisionPort, LocalizationResult, LocateInput, RefinementPort } from '../entities/contracts.js';
2
- import type { AnyLocateInput, WholeObjectLocateInput, WholeObjectLocalizationResult } from '../entities/whole-object.js';
3
1
  import type { WholeObjectIntervalPolicy } from '../processes/whole-object.js';
4
2
  import type { ImageRepresentationPort } from '../entities/representation.js';
5
- import type { ExtractInput, ExtractionResult, SegmentationPort } from '../entities/segmentation.js';
6
3
  import type { BoundaryViewPort } from '../entities/boundary-view.js';
7
- import type { ObjectProposalPort } from '../entities/object-proposals.js';
8
- import type { SegmentationBoxCheckPort } from '../entities/segmentation-verification.js';
9
- export interface ClassifierOptions {
10
- decision: DecisionPort;
11
- timeoutMs?: number;
12
- concurrency?: number;
13
- maxQueue?: number;
14
- maxInputBytes?: number;
15
- refinement?: RefinementPort;
16
- /** Caller-owned; classifier disposal never disposes a shared segmenter. */
17
- segmentation?: SegmentationPort;
18
- /** Optional caller-owned containment checker; by default reuses the injected decision port. */
19
- segmentationBoxCheck?: SegmentationBoxCheckPort;
20
- /** Explicit, caller-owned pixel-mask proposal strategy for whole-object operations. */
21
- objectProposals?: ObjectProposalPort;
22
- }
23
- export interface Classifier {
24
- classify(input: ClassifyInput): Promise<ClassificationResult>;
25
- locate(input: WholeObjectLocateInput): Promise<WholeObjectLocalizationResult>;
26
- locate(input: LocateInput): Promise<LocalizationResult>;
27
- locate(input: AnyLocateInput): Promise<LocalizationResult | WholeObjectLocalizationResult>;
28
- extract(input: ExtractInput): Promise<ExtractionResult>;
29
- dispose(): Promise<void>;
30
- }
4
+ import type { Classifier, ClassifierOptions } from './classifier-contracts.js';
5
+ export type { Classifier, ClassifierOptions } from './classifier-contracts.js';
31
6
  export declare function createClassifier(options: ClassifierOptions): Classifier;
32
- /** Internal benchmark composition. No research codec is exported by the npm entry points. */
33
- export declare function createResearchClassifier(options: ClassifierOptions, experimental?: ImageRepresentationPort, boundaryView?: BoundaryViewPort, intervalPolicy?: WholeObjectIntervalPolicy): Classifier;
7
+ /** Internal composition seam for benchmark helpers; not re-exported from public entry points. */
8
+ export declare function composeClassifier(options: ClassifierOptions, experimental?: ImageRepresentationPort, boundaryView?: BoundaryViewPort, intervalPolicy?: WholeObjectIntervalPolicy): Classifier;