@snaptrude/plugin-core 0.6.0 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/api-manifest.json +206 -704
  3. package/dist/api/core/index.d.ts +5 -0
  4. package/dist/api/core/index.d.ts.map +1 -1
  5. package/dist/api/core/proposals/index.d.ts +475 -0
  6. package/dist/api/core/proposals/index.d.ts.map +1 -0
  7. package/dist/api/design/create/index.d.ts +209 -0
  8. package/dist/api/design/create/index.d.ts.map +1 -1
  9. package/dist/api/design/doors/index.d.ts +159 -0
  10. package/dist/api/design/doors/index.d.ts.map +1 -1
  11. package/dist/api/design/furniture/index.d.ts +34 -5
  12. package/dist/api/design/furniture/index.d.ts.map +1 -1
  13. package/dist/api/design/index.d.ts +83 -0
  14. package/dist/api/design/index.d.ts.map +1 -1
  15. package/dist/api/design/lock.d.ts +26 -0
  16. package/dist/api/design/lock.d.ts.map +1 -1
  17. package/dist/api/design/materials/index.d.ts +159 -2
  18. package/dist/api/design/materials/index.d.ts.map +1 -1
  19. package/dist/api/design/query/index.d.ts +115 -5
  20. package/dist/api/design/query/index.d.ts.map +1 -1
  21. package/dist/api/design/selection/index.d.ts +2 -2
  22. package/dist/api/design/transform/index.d.ts +83 -2
  23. package/dist/api/design/transform/index.d.ts.map +1 -1
  24. package/dist/api/design/update/index.d.ts +168 -0
  25. package/dist/api/design/update/index.d.ts.map +1 -1
  26. package/dist/api/design/windows/index.d.ts +113 -2
  27. package/dist/api/design/windows/index.d.ts.map +1 -1
  28. package/dist/api/entity/story.d.ts +101 -7
  29. package/dist/api/entity/story.d.ts.map +1 -1
  30. package/dist/api/presentation/aiInspiration.d.ts +1967 -7
  31. package/dist/api/presentation/aiInspiration.d.ts.map +1 -1
  32. package/dist/api/presentation/import.d.ts +49 -4
  33. package/dist/api/presentation/import.d.ts.map +1 -1
  34. package/dist/api/presentation/index.d.ts +2 -3
  35. package/dist/api/presentation/index.d.ts.map +1 -1
  36. package/dist/api/presentation/views.d.ts +210 -5
  37. package/dist/api/presentation/views.d.ts.map +1 -1
  38. package/dist/api/program/areas.d.ts +42 -12
  39. package/dist/api/program/areas.d.ts.map +1 -1
  40. package/dist/api/program/index.d.ts +3 -11
  41. package/dist/api/program/index.d.ts.map +1 -1
  42. package/dist/api/program/layout.d.ts +186 -11
  43. package/dist/api/program/layout.d.ts.map +1 -1
  44. package/dist/errors/codes.d.ts +34 -0
  45. package/dist/errors/codes.d.ts.map +1 -0
  46. package/dist/errors/envelope.d.ts +56 -0
  47. package/dist/errors/envelope.d.ts.map +1 -0
  48. package/dist/errors/index.d.ts +6 -0
  49. package/dist/errors/index.d.ts.map +1 -0
  50. package/dist/errors/plugin-error.d.ts +69 -0
  51. package/dist/errors/plugin-error.d.ts.map +1 -0
  52. package/dist/host-utils.d.ts +4 -0
  53. package/dist/host-utils.d.ts.map +1 -1
  54. package/dist/index.cjs +1993 -1033
  55. package/dist/index.cjs.map +1 -1
  56. package/dist/index.d.ts +1 -0
  57. package/dist/index.d.ts.map +1 -1
  58. package/dist/index.js +1874 -1030
  59. package/dist/index.js.map +1 -1
  60. package/package.json +2 -1
  61. package/scripts/generate-manifest.test.mjs +77 -0
  62. package/src/api/core/index.ts +5 -0
  63. package/src/api/core/proposals/index.ts +509 -0
  64. package/src/api/design/create/index.ts +249 -0
  65. package/src/api/design/doors/index.ts +168 -0
  66. package/src/api/design/furniture/index.ts +36 -5
  67. package/src/api/design/index.ts +87 -0
  68. package/src/api/design/lock.ts +27 -0
  69. package/src/api/design/materials/index.ts +182 -2
  70. package/src/api/design/query/index.ts +81 -0
  71. package/src/api/design/transform/index.ts +74 -2
  72. package/src/api/design/update/index.ts +167 -0
  73. package/src/api/design/windows/index.ts +128 -2
  74. package/src/api/entity/story.ts +105 -7
  75. package/src/api/presentation/aiInspiration.ts +761 -7
  76. package/src/api/presentation/import.ts +45 -4
  77. package/src/api/presentation/index.ts +2 -3
  78. package/src/api/presentation/views.ts +221 -5
  79. package/src/api/program/areas.ts +34 -12
  80. package/src/api/program/index.ts +3 -11
  81. package/src/api/program/layout.ts +195 -11
  82. package/src/errors/codes.ts +136 -0
  83. package/src/errors/envelope.ts +75 -0
  84. package/src/errors/index.ts +21 -0
  85. package/src/errors/plugin-error.ts +134 -0
  86. package/src/host-utils.ts +4 -0
  87. package/src/index.ts +1 -0
  88. package/test/errors.test.mjs +184 -0
  89. package/api-manifest.full.json +0 -5600
@@ -9,8 +9,20 @@ import { PluginApiReturn } from "../../types"
9
9
  * three of the space-planning workflow that starts with
10
10
  * {@linkcode PluginProgramAdjacencyApi} (`program.adjacency`).
11
11
  *
12
- * _(Authored ahead both methods are optional until the host lands them in
13
- * the next increment, and are kept out of the discovery manifest until then.)_
12
+ * Both {@linkcode PluginProgramLayoutApi.arrange} and
13
+ * {@linkcode PluginProgramLayoutApi.pack} run as an **asynchronous backend
14
+ * job** on the space-solver service:
15
+ *
16
+ * 1. `arrange` / `pack` start the job and **return immediately** — they do
17
+ * not wait for the layout.
18
+ * 2. Poll {@linkcode PluginProgramLayoutApi.getState} until `status` is no
19
+ * longer `"running"` — a run can take up to 20 minutes.
20
+ * 3. {@linkcode PluginProgramLayoutApi.cancel} aborts an in-flight run.
21
+ *
22
+ * `arrange` produces several candidate layouts and **auto-commits the first
23
+ * solution** as one undoable edit (there is no interactive solution-review
24
+ * over the plugin boundary); `pack` re-shapes and applies its single result
25
+ * directly. Both are **Pro-plan-gated**, matching the product UI.
14
26
  *
15
27
  * Accessed via `snaptrude.program.layout`.
16
28
  */
@@ -19,7 +31,29 @@ export abstract class PluginProgramLayoutApi {
19
31
 
20
32
  /**
21
33
  * Arrange the spaces inside the envelope using the computed adjacency data.
22
- * _(Authored ahead — optional until the host lands.)_
34
+ *
35
+ * Starts the backend job and **returns immediately** — poll
36
+ * {@linkcode PluginProgramLayoutApi.getState} until `status` leaves
37
+ * `"running"` (a run can take up to 20 minutes). The solver produces
38
+ * several candidate layouts; this **auto-commits the first solution** as one
39
+ * undoable edit (no interactive review over the plugin boundary). Starting a
40
+ * run while one is in flight replaces it.
41
+ *
42
+ * With no `options`, operates on the eligible Room/Department masses on the
43
+ * active storey and auto-detects the single buildable envelope there.
44
+ *
45
+ * @param options - Optional {@linkcode PluginProgramLayoutRunArgs} — the
46
+ * space / department masses to arrange and the envelope to fit them in.
47
+ * Omitted fields fall back to the active-storey defaults.
48
+ * @returns A {@linkcode PluginProgramLayoutRunResult} — `{ success: true }`
49
+ * when the job was started. Solver failures surface through
50
+ * {@linkcode PluginProgramLayoutApi.getState} (`status: "inactive"`), not
51
+ * as a rejected call.
52
+ * @throws When the project is not on a Pro plan.
53
+ * @throws When a `spaceId` / `departmentId` / `envelopeId` does not resolve.
54
+ * @throws When more than one envelope is on the active storey and none was
55
+ * given (ambiguous).
56
+ * @throws When plugin writes are disabled.
23
57
  *
24
58
  * @examplePrompt Arrange the rooms in the envelope
25
59
  * @examplePrompt Lay out the departments inside the building envelope
@@ -28,14 +62,43 @@ export abstract class PluginProgramLayoutApi {
28
62
  * # Example
29
63
  * ```ts
30
64
  * const { success, error } = await snaptrude.program.layout.arrange()
31
- * if (!success) console.log("Arrange failed:", error)
65
+ * if (!success) throw new Error(error)
66
+ * // poll until the layout is applied
67
+ * let job = await snaptrude.program.layout.getState()
68
+ * while (job?.status === "running") {
69
+ * await new Promise((r) => setTimeout(r, 5000))
70
+ * job = await snaptrude.program.layout.getState()
71
+ * }
32
72
  * ```
33
73
  */
34
- public arrange?: () => PluginApiReturn<PluginProgramLayoutRunResult>
74
+ public abstract arrange(
75
+ options?: PluginProgramLayoutRunArgs,
76
+ ): PluginApiReturn<PluginProgramLayoutRunResult>
35
77
 
36
78
  /**
37
79
  * Pack the spaces into the envelope (a tighter fit than arrange).
38
- * _(Authored ahead — optional until the host lands.)_
80
+ *
81
+ * Like {@linkcode PluginProgramLayoutApi.arrange}, this starts the backend
82
+ * job and **returns immediately** — poll
83
+ * {@linkcode PluginProgramLayoutApi.getState} until `status` leaves
84
+ * `"running"` (up to 20 minutes). Pack re-shapes mass geometry to fit and
85
+ * **applies its single result directly** (no solution review). Starting a
86
+ * run while one is in flight replaces it.
87
+ *
88
+ * With no `options`, operates on the eligible Room/Department masses on the
89
+ * active storey and auto-detects the single buildable envelope there.
90
+ *
91
+ * @param options - Optional {@linkcode PluginProgramLayoutRunArgs} — same
92
+ * shape as `arrange`; omitted fields fall back to the active-storey
93
+ * defaults.
94
+ * @returns A {@linkcode PluginProgramLayoutRunResult} — `{ success: true }`
95
+ * when the job was started. Solver failures surface through
96
+ * {@linkcode PluginProgramLayoutApi.getState} (`status: "inactive"`).
97
+ * @throws When the project is not on a Pro plan.
98
+ * @throws When a `spaceId` / `departmentId` / `envelopeId` does not resolve.
99
+ * @throws When more than one envelope is on the active storey and none was
100
+ * given (ambiguous).
101
+ * @throws When plugin writes are disabled.
39
102
  *
40
103
  * @examplePrompt Pack the rooms into the envelope
41
104
  * @examplePrompt Fit the program spaces tightly into the building
@@ -43,20 +106,99 @@ export abstract class PluginProgramLayoutApi {
43
106
  *
44
107
  * # Example
45
108
  * ```ts
46
- * const { success, error } = await snaptrude.program.layout.pack()
47
- * if (!success) console.log("Pack failed:", error)
109
+ * const { success } = await snaptrude.program.layout.pack({ envelopeId: "be_..." })
110
+ * let job = await snaptrude.program.layout.getState()
111
+ * while (job?.status === "running") {
112
+ * await new Promise((r) => setTimeout(r, 5000))
113
+ * job = await snaptrude.program.layout.getState()
114
+ * }
115
+ * ```
116
+ */
117
+ public abstract pack(
118
+ options?: PluginProgramLayoutRunArgs,
119
+ ): PluginApiReturn<PluginProgramLayoutRunResult>
120
+
121
+ /**
122
+ * Get the state of the layout run.
123
+ *
124
+ * The polling read for the async job started by
125
+ * {@linkcode PluginProgramLayoutApi.arrange} /
126
+ * {@linkcode PluginProgramLayoutApi.pack}. `status` values:
127
+ *
128
+ * | Status | Meaning |
129
+ * |---|---|
130
+ * | `"running"` | A run is in flight — keep polling |
131
+ * | `"active"` | The run finished and its layout is applied to the model |
132
+ * | `"inactive"` | A run finished without applying a layout (the solver failed or found no solution) |
133
+ *
134
+ * @returns A {@linkcode PluginProgramLayoutStateResult} with the run
135
+ * `status`, or `null` when no run result is available (never ran or was
136
+ * cancelled).
137
+ *
138
+ * @examplePrompt Is the arrange done?
139
+ * @examplePrompt Check the status of the layout run
140
+ * @examplePrompt Did the pack finish?
141
+ *
142
+ * # Example
143
+ * ```ts
144
+ * const job = await snaptrude.program.layout.getState()
145
+ * if (job?.status === "active") console.log("layout applied")
146
+ * ```
147
+ */
148
+ public abstract getState(): PluginApiReturn<PluginProgramLayoutStateResult>
149
+
150
+ /**
151
+ * Cancel the in-flight layout run.
152
+ *
153
+ * Aborts the backend job and discards any pending solution. A no-op
154
+ * (returns `false`) when nothing is running.
155
+ *
156
+ * @returns `true` when a run was cancelled, `false` when nothing was
157
+ * running.
158
+ * @throws When plugin writes are disabled.
159
+ *
160
+ * @examplePrompt Cancel the arrange
161
+ * @examplePrompt Stop the running layout job
162
+ * @examplePrompt Abort the pack in envelope
163
+ *
164
+ * # Example
165
+ * ```ts
166
+ * await snaptrude.program.layout.cancel()
48
167
  * ```
49
168
  */
50
- public pack?: () => PluginApiReturn<PluginProgramLayoutRunResult>
169
+ public abstract cancel(): PluginApiReturn<boolean>
51
170
  }
52
171
 
172
+ /**
173
+ * Arguments for {@linkcode PluginProgramLayoutApi.arrange} /
174
+ * {@linkcode PluginProgramLayoutApi.pack}. All fields are optional — omitted
175
+ * fields fall back to the eligible masses and the single envelope on the
176
+ * active storey.
177
+ *
178
+ * | Property | Type | Description |
179
+ * |---|---|---|
180
+ * | `spaceIds` | `string[] \| undefined` | Component ids of the Room masses to lay out |
181
+ * | `departmentIds` | `string[] \| undefined` | Component ids of the Department masses to lay out |
182
+ * | `envelopeId` | `string \| undefined` | The envelope to fit into — a mass component id or a buildable-envelope handle (`be_…`); omit to auto-detect the single envelope on the active storey |
183
+ */
184
+ export const PluginProgramLayoutRunArgs = z.object({
185
+ spaceIds: z.array(z.string()).optional(),
186
+ departmentIds: z.array(z.string()).optional(),
187
+ envelopeId: z.string().optional(),
188
+ })
189
+ export type PluginProgramLayoutRunArgs = z.infer<
190
+ typeof PluginProgramLayoutRunArgs
191
+ >
192
+
53
193
  /**
54
194
  * Result of {@linkcode PluginProgramLayoutApi.arrange} /
55
- * {@linkcode PluginProgramLayoutApi.pack}.
195
+ * {@linkcode PluginProgramLayoutApi.pack} — reports whether the run was
196
+ * **started**, not whether the layout finished (poll
197
+ * {@linkcode PluginProgramLayoutApi.getState} for completion).
56
198
  *
57
199
  * | Property | Type | Description |
58
200
  * |---|---|---|
59
- * | `success` | `boolean` | Whether the layout run completed |
201
+ * | `success` | `boolean` | Whether the layout run was started |
60
202
  * | `error` | `string \| undefined` | Failure reason when `success` is `false` |
61
203
  */
62
204
  export const PluginProgramLayoutRunResult = z.object({
@@ -66,3 +208,45 @@ export const PluginProgramLayoutRunResult = z.object({
66
208
  export type PluginProgramLayoutRunResult = z.infer<
67
209
  typeof PluginProgramLayoutRunResult
68
210
  >
211
+
212
+ /**
213
+ * The status of a layout run.
214
+ *
215
+ * | Value | Meaning |
216
+ * |---|---|
217
+ * | `"running"` | A run is in flight — keep polling |
218
+ * | `"active"` | The run finished and its layout is applied to the model |
219
+ * | `"inactive"` | A run finished without applying a layout (the solver failed or found no solution) |
220
+ */
221
+ export const PluginProgramLayoutJobStatus = z.enum([
222
+ "running",
223
+ "active",
224
+ "inactive",
225
+ ])
226
+ export type PluginProgramLayoutJobStatus = z.infer<
227
+ typeof PluginProgramLayoutJobStatus
228
+ >
229
+
230
+ /**
231
+ * The state of a layout run.
232
+ *
233
+ * | Property | Type | Description |
234
+ * |---|---|---|
235
+ * | `status` | {@linkcode PluginProgramLayoutJobStatus} | `"running"` \| `"active"` \| `"inactive"` |
236
+ */
237
+ export const PluginProgramLayoutJobState = z.object({
238
+ status: PluginProgramLayoutJobStatus,
239
+ })
240
+ export type PluginProgramLayoutJobState = z.infer<
241
+ typeof PluginProgramLayoutJobState
242
+ >
243
+
244
+ /**
245
+ * Result of {@linkcode PluginProgramLayoutApi.getState} — the run state, or
246
+ * `null` when no run result is available (never ran or was cancelled).
247
+ */
248
+ export const PluginProgramLayoutStateResult =
249
+ PluginProgramLayoutJobState.nullable()
250
+ export type PluginProgramLayoutStateResult = z.infer<
251
+ typeof PluginProgramLayoutStateResult
252
+ >
@@ -0,0 +1,136 @@
1
+ /**
2
+ * The closed error-code registry — the single source of truth for every error
3
+ * that crosses the plugin wire (host → worker) or is minted client-side.
4
+ *
5
+ * APPEND-ONLY: codes are a published contract; never rename or remove one.
6
+ * Handle-resolution failures deliberately collapse to ONE code
7
+ * (`HANDLE_INVALID`) so error responses cannot be used as an existence /
8
+ * ownership oracle (PLUGIN_HANDLE_MIGRATION_HLD §6). `HANDLE_KIND_MISMATCH`
9
+ * stays distinct because the kind is information the caller already holds.
10
+ */
11
+ export const PLUGIN_ERROR_CODES = [
12
+ "VALIDATION",
13
+ "INVALID_RPC_FORMAT",
14
+ "METHOD_NOT_FOUND",
15
+ "METHOD_NOT_PERMITTED",
16
+ "HANDLE_INVALID",
17
+ "HANDLE_KIND_MISMATCH",
18
+ "RESOURCE_QUOTA_EXCEEDED",
19
+ "RATE_LIMITED",
20
+ "PRECONDITION_FAILED",
21
+ "OPERATION_FAILED",
22
+ "TIMEOUT",
23
+ "CALL_TIMEOUT",
24
+ "TRANSPORT_LOST",
25
+ "PLUGIN_NOT_READY",
26
+ "PLUGIN_TERMINATED",
27
+ "RESULT_NOT_SERIALIZABLE",
28
+ "RESULT_TOO_LARGE",
29
+ "BATCH_PARTIAL",
30
+ "STORY_UPDATE_FAILED",
31
+ "STORY_HEIGHT_REJECTED",
32
+ "NO_ACTIVE_STRUCTURE",
33
+ "NO_ELIGIBLE_ELEMENTS",
34
+ "PROPOSAL_SWITCH_BLOCKED",
35
+ "INTERNAL",
36
+ "UNKNOWN",
37
+ ] as const
38
+
39
+ export type PluginErrorCode = (typeof PLUGIN_ERROR_CODES)[number]
40
+
41
+ /**
42
+ * A known code, or a string outside the union — a plugin built against an
43
+ * older SDK may receive codes a newer host appended. Keeps autocomplete for
44
+ * known codes while staying open on the wire (forward compatibility).
45
+ */
46
+ export type WirePluginErrorCode = PluginErrorCode | (string & {})
47
+
48
+ export type PluginErrorCategory =
49
+ | "validation"
50
+ | "not_found"
51
+ | "permission"
52
+ | "handle"
53
+ | "quota"
54
+ | "timeout"
55
+ | "transport"
56
+ | "lifecycle"
57
+ | "execution"
58
+ | "internal"
59
+
60
+ /**
61
+ * Client-side metadata for a code. NOT carried on the wire — every field is a
62
+ * pure function of the code, and this table ships inside plugin-core, so both
63
+ * endpoints derive it locally.
64
+ */
65
+ export interface CodeMeta {
66
+ /** Family of the code; picks the `PluginError` sugar subclass. */
67
+ category: PluginErrorCategory
68
+ /** Fallback `hint` when the throw site provides none. */
69
+ hintTemplate?: string
70
+ }
71
+
72
+ export const CODE_META: Record<PluginErrorCode, CodeMeta> = {
73
+ VALIDATION: {
74
+ category: "validation",
75
+ hintTemplate: "Check details.issues for the failing argument.",
76
+ },
77
+ INVALID_RPC_FORMAT: { category: "validation" },
78
+ METHOD_NOT_FOUND: {
79
+ category: "not_found",
80
+ hintTemplate: "Check details.didYouMean for a close match.",
81
+ },
82
+ METHOD_NOT_PERMITTED: { category: "permission" },
83
+ HANDLE_INVALID: {
84
+ category: "handle",
85
+ hintTemplate: "Re-query the entity; do not cache handles across undo/reload.",
86
+ },
87
+ HANDLE_KIND_MISMATCH: { category: "handle" },
88
+ RESOURCE_QUOTA_EXCEEDED: {
89
+ category: "quota",
90
+ hintTemplate: "Release unused handles (core.handles.release) or use scopes.",
91
+ },
92
+ RATE_LIMITED: {
93
+ category: "quota",
94
+ hintTemplate: "Wait details.retryAfterMs before retrying.",
95
+ },
96
+ PRECONDITION_FAILED: { category: "execution" },
97
+ OPERATION_FAILED: { category: "execution" },
98
+ TIMEOUT: { category: "timeout" },
99
+ CALL_TIMEOUT: { category: "timeout" },
100
+ TRANSPORT_LOST: { category: "transport" },
101
+ PLUGIN_NOT_READY: { category: "lifecycle" },
102
+ PLUGIN_TERMINATED: { category: "lifecycle" },
103
+ RESULT_NOT_SERIALIZABLE: { category: "execution" },
104
+ RESULT_TOO_LARGE: { category: "execution" },
105
+ BATCH_PARTIAL: { category: "execution" },
106
+ STORY_UPDATE_FAILED: {
107
+ category: "execution",
108
+ hintTemplate: "The storey update could not be applied; re-read the storey and retry.",
109
+ },
110
+ STORY_HEIGHT_REJECTED: {
111
+ category: "execution",
112
+ hintTemplate: "The requested height was out of range; pick a value within the storey's limits.",
113
+ },
114
+ NO_ACTIVE_STRUCTURE: {
115
+ category: "execution",
116
+ hintTemplate: "Activate a structure before running this operation.",
117
+ },
118
+ NO_ELIGIBLE_ELEMENTS: {
119
+ category: "execution",
120
+ hintTemplate: "The storey has no elements eligible for this operation.",
121
+ },
122
+ PROPOSAL_SWITCH_BLOCKED: {
123
+ category: "execution",
124
+ hintTemplate: "Wait for the in-canvas agent run to finish, then retry.",
125
+ },
126
+ INTERNAL: {
127
+ category: "internal",
128
+ hintTemplate: "Host-side fault. Report with errorId.",
129
+ },
130
+ UNKNOWN: { category: "internal" },
131
+ }
132
+
133
+ /** Narrow an arbitrary string to a member of the closed code union. */
134
+ export function isPluginErrorCode(value: string): value is PluginErrorCode {
135
+ return (PLUGIN_ERROR_CODES as readonly string[]).includes(value)
136
+ }
@@ -0,0 +1,75 @@
1
+ import type { WirePluginErrorCode } from "./codes"
2
+
3
+ /**
4
+ * Structured error payload carried on the `{success: false}` branch of the RPC
5
+ * wire result, next to the legacy `error: string` field (additive — old
6
+ * clients ignore it, old hosts never set it).
7
+ *
8
+ * Errors cross the worker boundary as THIS plain object, never as a thrown
9
+ * class: Comlink's throw transfer strips subclasses and custom fields and
10
+ * leaks host stacks. plugin-client reconstructs a typed `PluginError` from it
11
+ * (`fromEnvelope`).
12
+ */
13
+ export const ERROR_ENVELOPE_VERSION = 1 as const
14
+
15
+ export interface ErrorEnvelope {
16
+ envelopeVersion: typeof ERROR_ENVELOPE_VERSION
17
+ code: WirePluginErrorCode
18
+ /**
19
+ * Human-readable failure description. For INTERNAL/UNKNOWN this is a GENERIC
20
+ * message — the real message and stack stay host-side, logged under
21
+ * `errorId` (the worker is untrusted; internals must not leak).
22
+ */
23
+ message: string
24
+ /**
25
+ * Per-occurrence id. For INTERNAL the host logs the real message and stack
26
+ * under this id (the sanitized message would otherwise be an undebuggable
27
+ * dead end). Other codes carry the id only to identify the occurrence in
28
+ * bug reports — the host does not log them. Client-minted ids carry a `c-`
29
+ * prefix.
30
+ */
31
+ errorId: string
32
+ /** Structured, JSON-safe, code-specific data (issues / retryAfterMs / didYouMean / handles…). */
33
+ details?: Record<string, unknown>
34
+ /**
35
+ * Wire id of the single primary offending handle, when the failure is
36
+ * handle-scoped. Multiple offenders go in `details.handles: string[]`.
37
+ * May echo ONLY ids the caller itself supplied (anti-oracle rule).
38
+ */
39
+ handle?: string
40
+ /** Dotted method path of the failed call (e.g. "design.boolean.union"). */
41
+ methodPath?: string
42
+ /** Machine-actionable fix suggestion (written for LLM plugin authors). */
43
+ hint?: string
44
+ }
45
+
46
+ /**
47
+ * Structural guard for a wire value claiming to be an `ErrorEnvelope`.
48
+ *
49
+ * Checks shape only — deliberately does NOT reject codes outside the known
50
+ * union, so envelopes from a newer host still pass (forward compatibility).
51
+ */
52
+ export function isErrorEnvelope(value: unknown): value is ErrorEnvelope {
53
+ if (typeof value !== "object" || value === null) return false
54
+ const record = value as Record<string, unknown>
55
+ return (
56
+ record.envelopeVersion === ERROR_ENVELOPE_VERSION &&
57
+ typeof record.code === "string" &&
58
+ typeof record.message === "string" &&
59
+ typeof record.errorId === "string"
60
+ )
61
+ }
62
+
63
+ let idCounter = 0
64
+
65
+ /**
66
+ * Mint a per-occurrence error id. Uses `crypto.randomUUID` when available
67
+ * (browser main thread and workers both have it); falls back to a
68
+ * counter+random suffix — uniqueness within a session is all that is needed.
69
+ */
70
+ export function newErrorId(prefix = ""): string {
71
+ const cryptoApi = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto
72
+ if (cryptoApi?.randomUUID) return `${prefix}${cryptoApi.randomUUID()}`
73
+ idCounter += 1
74
+ return `${prefix}${Date.now().toString(36)}-${idCounter}-${Math.random().toString(36).slice(2, 10)}`
75
+ }
@@ -0,0 +1,21 @@
1
+ export { PLUGIN_ERROR_CODES, CODE_META, isPluginErrorCode } from "./codes"
2
+ export type { PluginErrorCode, WirePluginErrorCode, PluginErrorCategory, CodeMeta } from "./codes"
3
+
4
+ export { ERROR_ENVELOPE_VERSION, isErrorEnvelope, newErrorId } from "./envelope"
5
+ export type { ErrorEnvelope } from "./envelope"
6
+
7
+ export {
8
+ PluginError,
9
+ PluginValidationError,
10
+ PluginNotFoundError,
11
+ PluginPermissionError,
12
+ PluginHandleError,
13
+ PluginQuotaError,
14
+ PluginTimeoutError,
15
+ PluginTransportError,
16
+ PluginLifecycleError,
17
+ PluginExecutionError,
18
+ PluginInternalError,
19
+ fromEnvelope,
20
+ makeClientEnvelope,
21
+ } from "./plugin-error"
@@ -0,0 +1,134 @@
1
+ import { CODE_META, isPluginErrorCode } from "./codes"
2
+ import type { PluginErrorCategory, PluginErrorCode, WirePluginErrorCode } from "./codes"
3
+ import { ERROR_ENVELOPE_VERSION, newErrorId } from "./envelope"
4
+ import type { ErrorEnvelope } from "./envelope"
5
+
6
+ /**
7
+ * Cross-copy brand: a plugin bundle may contain its OWN copy of this module,
8
+ * in which case `instanceof` fails across the two class identities.
9
+ * `Symbol.for` resolves to the same symbol in every copy within a realm, so
10
+ * `PluginError.is()` keeps working. Canonical check = `.is()` + `code`.
11
+ */
12
+ const BRAND = Symbol.for("snaptrude.pluginError")
13
+
14
+ interface Branded {
15
+ [BRAND]?: boolean
16
+ }
17
+
18
+ /**
19
+ * Typed error every failed plugin API call rejects with.
20
+ *
21
+ * Rehydrated client-side from the wire `ErrorEnvelope` (`fromEnvelope`) — the
22
+ * class itself never crosses the worker boundary. Branch on the stable string
23
+ * `code`; use `PluginError.is()` rather than `instanceof` (a bundled duplicate
24
+ * SDK copy breaks `instanceof`, never the brand).
25
+ *
26
+ * @example
27
+ * ```ts
28
+ * try {
29
+ * await snaptrude.design.boolean.union(handles)
30
+ * } catch (e) {
31
+ * if (PluginError.is(e) && e.code === "RATE_LIMITED") {
32
+ * await sleep(e.details?.retryAfterMs as number)
33
+ * } else {
34
+ * throw e
35
+ * }
36
+ * }
37
+ * ```
38
+ */
39
+ export class PluginError extends Error {
40
+ readonly code: WirePluginErrorCode
41
+ readonly errorId: string
42
+ readonly details?: Record<string, unknown>
43
+ readonly handle?: string
44
+ readonly methodPath?: string
45
+ readonly hint?: string
46
+
47
+ constructor(envelope: ErrorEnvelope) {
48
+ super(envelope.message)
49
+ this.name = new.target.name
50
+ this.code = envelope.code
51
+ this.errorId = envelope.errorId
52
+ this.details = envelope.details
53
+ this.handle = envelope.handle
54
+ this.methodPath = envelope.methodPath
55
+ this.hint = envelope.hint ?? hintFor(envelope.code)
56
+ ;(this as Branded)[BRAND] = true
57
+ }
58
+
59
+ /** Canonical check — survives bundled duplicate SDK copies where `instanceof` fails. */
60
+ static is(value: unknown): value is PluginError {
61
+ return (
62
+ typeof value === "object" &&
63
+ value !== null &&
64
+ (value as Branded)[BRAND] === true
65
+ )
66
+ }
67
+
68
+ /** Derived (not wire-carried) family of the code; unknown codes map to "internal". */
69
+ get category(): PluginErrorCategory {
70
+ return isPluginErrorCode(this.code) ? CODE_META[this.code].category : "internal"
71
+ }
72
+ }
73
+
74
+ // Category sugar — same brand, so `PluginError.is()` matches all of them.
75
+ // Convenience for single-SDK-copy plugins; docs teach `.is()` + `code`.
76
+ export class PluginValidationError extends PluginError {}
77
+ export class PluginNotFoundError extends PluginError {}
78
+ export class PluginPermissionError extends PluginError {}
79
+ export class PluginHandleError extends PluginError {}
80
+ export class PluginQuotaError extends PluginError {}
81
+ export class PluginTimeoutError extends PluginError {}
82
+ export class PluginTransportError extends PluginError {}
83
+ export class PluginLifecycleError extends PluginError {}
84
+ export class PluginExecutionError extends PluginError {}
85
+ export class PluginInternalError extends PluginError {}
86
+
87
+ type PluginErrorConstructor = new (envelope: ErrorEnvelope) => PluginError
88
+
89
+ const CATEGORY_CLASS: Record<PluginErrorCategory, PluginErrorConstructor> = {
90
+ validation: PluginValidationError,
91
+ not_found: PluginNotFoundError,
92
+ permission: PluginPermissionError,
93
+ handle: PluginHandleError,
94
+ quota: PluginQuotaError,
95
+ timeout: PluginTimeoutError,
96
+ transport: PluginTransportError,
97
+ lifecycle: PluginLifecycleError,
98
+ execution: PluginExecutionError,
99
+ internal: PluginInternalError,
100
+ }
101
+
102
+ function hintFor(code: WirePluginErrorCode): string | undefined {
103
+ return isPluginErrorCode(code) ? CODE_META[code].hintTemplate : undefined
104
+ }
105
+
106
+ /**
107
+ * Rehydrate a wire envelope into the typed error the plugin catches.
108
+ * A code outside the known union (newer host) constructs the base
109
+ * `PluginError` with the code preserved verbatim.
110
+ */
111
+ export function fromEnvelope(envelope: ErrorEnvelope): PluginError {
112
+ if (!isPluginErrorCode(envelope.code)) return new PluginError(envelope)
113
+ const ErrorClass = CATEGORY_CLASS[CODE_META[envelope.code].category]
114
+ return new ErrorClass(envelope)
115
+ }
116
+
117
+ /**
118
+ * Build an envelope for a CLIENT-detected failure (transport rejection,
119
+ * legacy host without `errorInfo`). Host-originated envelopes are built by
120
+ * the host's `toErrorEnvelope` mapper, never by this.
121
+ */
122
+ export function makeClientEnvelope(
123
+ code: PluginErrorCode,
124
+ message: string,
125
+ extra?: Partial<Pick<ErrorEnvelope, "details" | "handle" | "methodPath" | "hint">>
126
+ ): ErrorEnvelope {
127
+ return {
128
+ envelopeVersion: ERROR_ENVELOPE_VERSION,
129
+ code,
130
+ message,
131
+ errorId: newErrorId("c-"),
132
+ ...extra,
133
+ }
134
+ }
package/src/host-utils.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { PluginApi } from "./api"
2
+ import type { ErrorEnvelope } from "./errors"
2
3
 
3
4
  // -- Type Utilities for inferring method paths from the class hierarchy ------
4
5
 
@@ -60,5 +61,8 @@ export type PluginApiCallResult<M extends PluginApiMethod> =
60
61
  export type PluginApiCallWrappedResult<M extends PluginApiMethod> = {
61
62
  success: boolean;
62
63
  data?: PluginApiCallResult<M>;
64
+ /** Legacy failure message — kept verbatim for already-published plugins. */
63
65
  error?: string;
66
+ /** Structured failure (hosts ≥ error-envelope rollout). Present iff `success` is false. */
67
+ errorInfo?: ErrorEnvelope;
64
68
  }
package/src/index.ts CHANGED
@@ -2,3 +2,4 @@ export * from "./api"
2
2
  export * from "./types"
3
3
  export * from "./host-utils"
4
4
  export * from "./handles"
5
+ export * from "./errors"