@danypops/vehicle-core 0.16.0 → 0.17.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 (123) hide show
  1. package/README.md +12 -0
  2. package/dist/{vehicle-approvals.d.ts → approvals/approval.d.ts} +4 -11
  3. package/dist/{vehicle-approvals.js → approvals/approval.js} +53 -12
  4. package/dist/approvals/index.d.ts +1 -0
  5. package/dist/approvals/index.js +1 -0
  6. package/dist/client/client.d.ts +29 -0
  7. package/dist/client/client.js +1 -0
  8. package/dist/client/index.d.ts +1 -0
  9. package/dist/client/index.js +1 -0
  10. package/dist/content/content.d.ts +32 -0
  11. package/dist/content/content.js +25 -0
  12. package/dist/content/index.d.ts +1 -0
  13. package/dist/content/index.js +1 -0
  14. package/dist/{vehicle-errors.d.ts → errors/error.d.ts} +22 -10
  15. package/dist/{vehicle-errors.js → errors/error.js} +20 -0
  16. package/dist/errors/index.d.ts +1 -0
  17. package/dist/errors/index.js +1 -0
  18. package/dist/events/event.d.ts +42 -0
  19. package/dist/events/event.js +35 -0
  20. package/dist/events/index.d.ts +1 -0
  21. package/dist/events/index.js +1 -0
  22. package/dist/idempotency/index.d.ts +1 -0
  23. package/dist/idempotency/index.js +1 -0
  24. package/dist/idempotency/receipt.d.ts +66 -0
  25. package/dist/idempotency/receipt.js +42 -0
  26. package/dist/index.d.ts +26 -7
  27. package/dist/index.js +26 -7
  28. package/dist/jobs/identity.d.ts +11 -0
  29. package/dist/jobs/identity.js +13 -0
  30. package/dist/jobs/index.d.ts +7 -0
  31. package/dist/jobs/index.js +7 -0
  32. package/dist/jobs/replay.d.ts +8 -0
  33. package/dist/jobs/replay.js +9 -0
  34. package/dist/jobs/retention.d.ts +26 -0
  35. package/dist/jobs/retention.js +39 -0
  36. package/dist/jobs/steer.d.ts +23 -0
  37. package/dist/jobs/steer.js +41 -0
  38. package/dist/jobs/termination.d.ts +5 -0
  39. package/dist/jobs/termination.js +11 -0
  40. package/dist/jobs/wake-log.d.ts +39 -0
  41. package/dist/jobs/wake-log.js +65 -0
  42. package/dist/jobs/wire.d.ts +47 -0
  43. package/dist/jobs/wire.js +1 -0
  44. package/dist/manifest/index.d.ts +1 -0
  45. package/dist/manifest/index.js +1 -0
  46. package/dist/manifest/manifest.d.ts +49 -0
  47. package/dist/manifest/manifest.js +1 -0
  48. package/dist/operations/context.d.ts +52 -0
  49. package/dist/operations/context.js +1 -0
  50. package/dist/operations/effect.d.ts +3 -0
  51. package/dist/operations/effect.js +2 -0
  52. package/dist/operations/index.d.ts +3 -0
  53. package/dist/operations/index.js +3 -0
  54. package/dist/operations/operation.d.ts +98 -0
  55. package/dist/operations/operation.js +79 -0
  56. package/dist/{atomic-json.d.ts → persistence/atomic-json.d.ts} +1 -2
  57. package/dist/{atomic-json.js → persistence/atomic-json.js} +1 -2
  58. package/dist/persistence/index.d.ts +1 -0
  59. package/dist/persistence/index.js +1 -0
  60. package/dist/schedules/index.d.ts +1 -0
  61. package/dist/schedules/index.js +1 -0
  62. package/dist/{vehicle-scheduler.d.ts → schedules/schedule.d.ts} +23 -9
  63. package/dist/schedules/schedule.js +61 -0
  64. package/dist/schemas/codec.d.ts +25 -0
  65. package/dist/schemas/codec.js +7 -0
  66. package/dist/schemas/index.d.ts +4 -0
  67. package/dist/schemas/index.js +4 -0
  68. package/dist/schemas/json.d.ts +7 -0
  69. package/dist/schemas/json.js +14 -0
  70. package/dist/schemas/loose-object.d.ts +20 -0
  71. package/dist/schemas/loose-object.js +73 -0
  72. package/dist/schemas/presentation.d.ts +11 -0
  73. package/dist/schemas/presentation.js +22 -0
  74. package/dist/watches/index.d.ts +1 -0
  75. package/dist/watches/index.js +1 -0
  76. package/dist/{vehicle-watchers.d.ts → watches/registry.d.ts} +2 -9
  77. package/dist/{vehicle-watchers.js → watches/registry.js} +2 -9
  78. package/package.json +5 -1
  79. package/src/{vehicle-approvals.ts → approvals/approval.ts} +47 -13
  80. package/src/approvals/index.ts +1 -0
  81. package/src/client/client.ts +31 -0
  82. package/src/client/index.ts +1 -0
  83. package/src/content/content.ts +46 -0
  84. package/src/content/index.ts +1 -0
  85. package/src/{vehicle-errors.ts → errors/error.ts} +32 -9
  86. package/src/errors/index.ts +1 -0
  87. package/src/events/event.ts +72 -0
  88. package/src/events/index.ts +1 -0
  89. package/src/idempotency/index.ts +1 -0
  90. package/src/idempotency/receipt.ts +97 -0
  91. package/src/index.ts +26 -7
  92. package/src/jobs/identity.ts +13 -0
  93. package/src/jobs/index.ts +7 -0
  94. package/src/jobs/replay.ts +17 -0
  95. package/src/jobs/retention.ts +59 -0
  96. package/src/jobs/steer.ts +49 -0
  97. package/src/jobs/termination.ts +13 -0
  98. package/src/jobs/wake-log.ts +98 -0
  99. package/src/jobs/wire.ts +51 -0
  100. package/src/manifest/index.ts +1 -0
  101. package/src/manifest/manifest.ts +52 -0
  102. package/src/operations/context.ts +56 -0
  103. package/src/operations/effect.ts +3 -0
  104. package/src/operations/index.ts +3 -0
  105. package/src/operations/operation.ts +184 -0
  106. package/src/{atomic-json.ts → persistence/atomic-json.ts} +1 -2
  107. package/src/persistence/index.ts +1 -0
  108. package/src/schedules/index.ts +1 -0
  109. package/src/{vehicle-scheduler.ts → schedules/schedule.ts} +32 -9
  110. package/src/schemas/codec.ts +30 -0
  111. package/src/schemas/index.ts +4 -0
  112. package/src/schemas/json.ts +17 -0
  113. package/src/schemas/loose-object.ts +82 -0
  114. package/src/schemas/presentation.ts +28 -0
  115. package/src/watches/index.ts +1 -0
  116. package/src/{vehicle-watchers.ts → watches/registry.ts} +2 -9
  117. package/dist/vehicle-contract.d.ts +0 -347
  118. package/dist/vehicle-contract.js +0 -219
  119. package/dist/vehicle-jobs.d.ts +0 -159
  120. package/dist/vehicle-jobs.js +0 -182
  121. package/dist/vehicle-scheduler.js +0 -33
  122. package/src/vehicle-contract.ts +0 -563
  123. package/src/vehicle-jobs.ts +0 -305
@@ -1,563 +0,0 @@
1
- import type {
2
- VehicleJobSnapshot,
3
- VehicleJobSubmitOptions,
4
- VehicleJobSubmitResult,
5
- VehicleJobTailResult,
6
- VehicleJobWakeBudget,
7
- } from "./vehicle-jobs.js";
8
-
9
- export type JsonPrimitive = string | number | boolean | null;
10
- export type JsonValue = JsonPrimitive | readonly JsonValue[] | { readonly [key: string]: JsonValue };
11
- export type JsonSchema = Readonly<Record<string, JsonValue>>;
12
-
13
- /** Shared defense-in-depth vocabulary for credential-shaped fields at every Vehicle projection boundary. */
14
- export const VEHICLE_CREDENTIAL_FIELD_NAMES = Object.freeze([
15
- "password",
16
- "token",
17
- "accessToken",
18
- "refreshToken",
19
- "apiKey",
20
- "secret",
21
- "authorization",
22
- "credential",
23
- ] as const);
24
-
25
- const NORMALIZED_VEHICLE_CREDENTIAL_FIELD_NAMES = new Set(
26
- VEHICLE_CREDENTIAL_FIELD_NAMES.map((name) => name.replace(/[^a-z0-9]/gi, "").toLowerCase()),
27
- );
28
-
29
- /** Case/separator-insensitive credential-name check used as a fallback when a schema annotation is missing. */
30
- export function isVehicleCredentialFieldName(name: string): boolean {
31
- return NORMALIZED_VEHICLE_CREDENTIAL_FIELD_NAMES.has(name.replace(/[^a-z0-9]/gi, "").toLowerCase());
32
- }
33
-
34
- /**
35
- * JSON Schema property annotation consumed by human-facing Vehicle adapters.
36
- * `omit` hides the field; `summarize` may show shape/size but never its value.
37
- * Standard `writeOnly: true` and `format: "password"` always imply omission.
38
- */
39
- export const VEHICLE_SCHEMA_PRESENTATION_EXTENSION = "x-vehicle-presentation" as const;
40
- export type VehicleSchemaPresentation = "omit" | "summarize";
41
-
42
- export interface VehicleSchemaIssue {
43
- readonly path: readonly (string | number)[];
44
- readonly message: string;
45
- }
46
-
47
- export type VehicleSchemaResult<T> =
48
- | { readonly success: true; readonly value: T }
49
- | { readonly success: false; readonly issues?: readonly VehicleSchemaIssue[] };
50
-
51
- /**
52
- * A serializable, descriptive `jsonSchema` (surfaced to a client or Pi tool
53
- * projection) paired with a real `safeParse` that actually enforces it at
54
- * runtime -- a Vehicle registry's own `invoke()` only ever calls
55
- * `safeParse`; `jsonSchema` alone is never itself enforced, so a codec that
56
- * only sets `jsonSchema` without a matching `safeParse` is a documentation
57
- * gesture, not an honest contract.
58
- */
59
- export interface VehicleSchemaCodec<T> {
60
- readonly jsonSchema: JsonSchema;
61
- safeParse(value: unknown): VehicleSchemaResult<T>;
62
- }
63
-
64
- export function defineVehicleSchema<T>(codec: VehicleSchemaCodec<T>): VehicleSchemaCodec<T> {
65
- return Object.freeze({
66
- jsonSchema: cloneJson(codec.jsonSchema),
67
- safeParse: codec.safeParse,
68
- });
69
- }
70
-
71
- export interface LooseObjectProperty {
72
- readonly type: string;
73
- readonly enum?: readonly string[];
74
- }
75
-
76
- /**
77
- * A VehicleRegistry only ever calls a schema's own safeParse -- jsonSchema is
78
- * descriptive metadata surfaced to a client/Pi projection, never itself
79
- * enforced at runtime -- so a declared `enum` has to be checked here for
80
- * real, or it's a documentation gesture, not an honest contract. Every
81
- * consumer projecting a plain-object input onto a VehicleOperation needs the
82
- * same required/enum checks; this is that check written once.
83
- */
84
- export function defineLooseObjectSchema(
85
- properties: Record<string, LooseObjectProperty>,
86
- required: readonly string[] = [],
87
- ): VehicleSchemaCodec<Record<string, unknown>> {
88
- return defineVehicleSchema<Record<string, unknown>>({
89
- // LooseObjectProperty's named fields (type, enum) are all JSON-value-shaped
90
- // at runtime, but TypeScript's structural check against the recursive
91
- // JsonValue union doesn't see that through a plain interface -- the cast
92
- // is a type-system limitation, not a runtime concern.
93
- jsonSchema: { type: "object", properties: properties as unknown as JsonValue, required: [...required], additionalProperties: false },
94
- safeParse(value) {
95
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
96
- return { success: false, issues: [{ path: [], message: "input must be an object" }] };
97
- }
98
- const input = value as Record<string, unknown>;
99
- for (const key of required) {
100
- if (!(key in input)) return { success: false, issues: [{ path: [key], message: `${key} is required` }] };
101
- }
102
- for (const [key, schema] of Object.entries(properties)) {
103
- if (!schema.enum || !(key in input)) continue;
104
- if (!schema.enum.includes(input[key] as string)) {
105
- return { success: false, issues: [{ path: [key], message: `${key} must be one of ${schema.enum.join(", ")}` }] };
106
- }
107
- }
108
- return { success: true, value: input };
109
- },
110
- });
111
- }
112
-
113
- /** Accepts any value unvalidated -- for an operation whose output shape isn't worth a dedicated schema (an internal/low-stakes result, or one already validated upstream by the domain logic it wraps). */
114
- export const passthroughVehicleSchema: VehicleSchemaCodec<unknown> = defineVehicleSchema<unknown>({
115
- jsonSchema: { type: "object" },
116
- safeParse: (value) => ({ success: true, value }),
117
- });
118
-
119
- /**
120
- * A block of narrative text meant to be read by the model, not parsed as
121
- * data -- same field name and shape MCP's own CallToolResult.content and
122
- * Pi's own ToolDefinition.execute() return already use, so a Vehicle
123
- * operation adopting this needs no translation layer at either boundary.
124
- * Only the "text" variant exists here; there's no Vehicle use case yet for
125
- * MCP's image/audio/resource-link block kinds.
126
- */
127
- export interface VehicleContentBlock {
128
- readonly type: "text";
129
- readonly text: string;
130
- }
131
-
132
- /**
133
- * An operation's Output type can intersect this to carry its own
134
- * model-facing narrative alongside its structured data, e.g.
135
- * `type RunOutput = { runId: string; created: Task[] } & WithVehicleContent`.
136
- * The operation itself builds `content` since it's the only code that
137
- * actually knows how to describe what it computed -- never a per-consumer
138
- * override bolted on wherever the operation happens to get registered.
139
- */
140
- export interface WithVehicleContent {
141
- readonly content?: readonly VehicleContentBlock[];
142
- }
143
-
144
- /**
145
- * Reads an operation's own `content` blocks off its output when present and
146
- * well-formed, so a generic Vehicle client can prefer them over dumping raw
147
- * JSON at the model -- without knowing anything about the operation's own
148
- * domain shape. Returns undefined for a malformed or absent `content` field;
149
- * the caller falls back to its own default (formatted JSON) rather than
150
- * risk forwarding partial/garbled blocks.
151
- */
152
- export function extractVehicleContent(output: unknown): readonly VehicleContentBlock[] | undefined {
153
- if (typeof output !== "object" || output === null || Array.isArray(output)) return undefined;
154
- const content = (output as { readonly content?: unknown }).content;
155
- if (!Array.isArray(content) || content.length === 0) return undefined;
156
- const blocks: VehicleContentBlock[] = [];
157
- for (const block of content) {
158
- if (typeof block !== "object" || block === null) return undefined;
159
- const { type, text } = block as { readonly type?: unknown; readonly text?: unknown };
160
- if (type !== "text" || typeof text !== "string") return undefined;
161
- blocks.push({ type: "text", text });
162
- }
163
- return blocks;
164
- }
165
-
166
- export type VehicleEffect = "read" | "local-write" | "external-write" | "destructive" | "open-world";
167
-
168
- export type VehicleIdempotency =
169
- | { readonly mode: "safe" }
170
- | { readonly mode: "keyed"; readonly retentionMs: number }
171
- | { readonly mode: "unsafe" };
172
-
173
- export interface VehicleLimits {
174
- readonly defaultTimeoutMs: number;
175
- readonly maxTimeoutMs: number;
176
- readonly maxRequestBytes: number;
177
- readonly maxResponseBytes: number;
178
- }
179
-
180
- /** One structured, documented failure mode a {@link VehicleOperationDescriptor} declares up front -- part of the operation's own serializable contract, not an ad hoc thrown Error a caller has to reverse-engineer from a message string. */
181
- export interface VehicleFailureDescriptor {
182
- readonly code: string;
183
- readonly description: string;
184
- }
185
-
186
- /** Declares an operation safe to run as a Vehicle Job (detached, polled/tailed/canceled by id). Absent means live-invoke only. */
187
- export interface VehicleBackgroundCapability {
188
- readonly supported: true;
189
- readonly defaultWakeBudget: VehicleJobWakeBudget;
190
- readonly maxWakeBudget: VehicleJobWakeBudget;
191
- }
192
-
193
- /**
194
- * The serializable half of a Vehicle operation -- name, version, schemas,
195
- * ownership-implying permissions, effect classification, idempotency,
196
- * streaming/long-running capability, request/response limits, and declared
197
- * {@link VehicleFailureDescriptor} failure modes. Kept separate from the
198
- * executable {@link VehicleOperationHandler} on purpose: a manifest, a Pi
199
- * tool projection, or a client's own capability check can all inspect this
200
- * shape without ever touching (or needing to trust) the implementation
201
- * behind it.
202
- */
203
- export interface VehicleOperationDescriptor {
204
- readonly name: string;
205
- readonly version: number;
206
- readonly description: string;
207
- readonly inputSchema: JsonSchema;
208
- readonly outputSchema: JsonSchema;
209
- readonly permissions: readonly string[];
210
- readonly effect: VehicleEffect;
211
- readonly idempotency: VehicleIdempotency;
212
- readonly streaming: boolean;
213
- readonly longRunning: boolean;
214
- readonly limits: VehicleLimits;
215
- readonly errors: readonly VehicleFailureDescriptor[];
216
- readonly background?: VehicleBackgroundCapability;
217
- /**
218
- * Owner-declared override for whether this specific operation is ever a candidate for
219
- * approval gating, independent of its `effect`. Undefined (the default) means "derive it
220
- * from `effect` against the registry's own requireApprovalForEffects set instead" --
221
- * VehicleRegistry.manifest()'s own resolution rule, unchanged for every existing
222
- * operation that never sets this.
223
- *
224
- * Exists because VehicleEffect's five values are coarse enough that two operations a
225
- * real owner classifies very differently (e.g. "restart an already-installed,
226
- * already-vetted service" vs. "sync a read-only catalog mirror") can land in the same
227
- * effect bucket (both external-write) -- no single requireApprovalForEffects set can
228
- * gate one without also gating the other. The owner who registers the operation knows
229
- * its real risk far better than a 5-value enum can; this lets them say so directly.
230
- */
231
- readonly requiresApproval?: boolean;
232
- }
233
-
234
- export interface VehicleOperation<Input, Output> {
235
- readonly descriptor: VehicleOperationDescriptor;
236
- readonly input: VehicleSchemaCodec<Input>;
237
- readonly output: VehicleSchemaCodec<Output>;
238
- }
239
-
240
- export interface DefineVehicleOperationOptions<Input, Output> {
241
- readonly name: string;
242
- readonly version: number;
243
- readonly description: string;
244
- readonly input: VehicleSchemaCodec<Input>;
245
- readonly output: VehicleSchemaCodec<Output>;
246
- readonly permissions?: readonly string[];
247
- readonly effect: VehicleEffect;
248
- readonly idempotency: VehicleIdempotency;
249
- readonly streaming?: boolean;
250
- readonly longRunning?: boolean;
251
- readonly limits: VehicleLimits;
252
- readonly errors?: readonly VehicleFailureDescriptor[];
253
- readonly background?: VehicleBackgroundCapability;
254
- /** See {@link VehicleOperationDescriptor.requiresApproval}. */
255
- readonly requiresApproval?: boolean;
256
- }
257
-
258
- export interface VehiclePrincipal {
259
- readonly id: string;
260
- readonly claims?: Readonly<Record<string, JsonValue>>;
261
- }
262
-
263
- /**
264
- * callerSessionId/callerProjectRoot identify the real host session (e.g. one Pi TUI process) that
265
- * originated this call, and its working directory at call time -- a generic ownership/attribution
266
- * hook any operation handler can read (e.g. scoping a background subscription to the session or
267
- * project that created it), distinct from both:
268
- * - correlationId: a caller-CHOSEN id deliberately meant to span several separate invoke() calls
269
- * (a batch/business-transaction id), not an automatically-derived caller identity.
270
- * - principal: broader identity/claims used for permission and approval decisions, usually a
271
- * fixed per-extension value (e.g. {id: "pi-pipes"}), not a distinguishing per-session id.
272
- * A Pi projection layer (see vehicle-client-pi's invokeVehicleOperation) auto-derives both from
273
- * context.sessionManager.getSessionId()/context.cwd on every call, the same way it already
274
- * auto-derives correlationId -- a handler that never reads them pays nothing extra.
275
- */
276
- export interface VehicleInvocationOptions {
277
- readonly operationId?: string;
278
- readonly correlationId?: string;
279
- readonly callerSessionId?: string;
280
- readonly callerProjectRoot?: string;
281
- readonly signal?: AbortSignal;
282
- readonly deadline?: number;
283
- readonly permissions?: readonly string[];
284
- readonly principal?: VehiclePrincipal;
285
- readonly idempotencyKey?: string;
286
- readonly expectedRevision?: string | number;
287
- readonly approvalCapability?: string;
288
- readonly onProgress?: (progress: unknown) => void;
289
- }
290
-
291
- export interface VehicleOperationContext<Input> {
292
- readonly input: Input;
293
- readonly operationId: string;
294
- readonly correlationId?: string;
295
- /** See VehicleInvocationOptions's own doc comment. */
296
- readonly callerSessionId?: string;
297
- /** See VehicleInvocationOptions's own doc comment. */
298
- readonly callerProjectRoot?: string;
299
- readonly signal: AbortSignal;
300
- readonly deadline: number;
301
- readonly permissions: readonly string[];
302
- readonly principal?: VehiclePrincipal;
303
- readonly idempotencyKey?: string;
304
- readonly expectedRevision?: string | number;
305
- readonly approvalCapability?: string;
306
- /** Set only for a job execution (VehicleJobStore.submit()); undefined for a plain invoke(). A handler that wants mid-flight input opts in with `for await (const input of context.steerInputs ?? [])`. */
307
- readonly steerInputs?: AsyncIterable<unknown>;
308
- reportProgress(progress: unknown): void;
309
- }
310
-
311
- export type VehicleOperationHandler<Input, Output> = (context: VehicleOperationContext<Input>) => Promise<Output>;
312
-
313
- export interface VehicleOperationBinding<Input, Output> {
314
- readonly operation: VehicleOperation<Input, Output>;
315
- bind(): VehicleOperationHandler<Input, Output>;
316
- }
317
-
318
- export interface VehicleManifestIdentity {
319
- readonly name: string;
320
- readonly version: string;
321
- readonly description: string;
322
- readonly guidance?: readonly string[];
323
- }
324
-
325
- /**
326
- * A manifest's own view of an operation: the static descriptor plus
327
- * whether it's currently usable on this particular server instance right
328
- * now. Availability is a runtime property of a live registry (a
329
- * credential got configured or removed), never baked into the static
330
- * descriptor defineVehicleOperation() produces -- two manifest() calls
331
- * against the same registry can report different availability for the
332
- * exact same descriptor.
333
- */
334
- export interface VehicleManifestOperation extends VehicleOperationDescriptor {
335
- readonly available: boolean;
336
- readonly unavailableReason?: string;
337
- /**
338
- * The registry's own, live, fully-resolved answer to "does invoking this operation right
339
- * now require approval" -- accounts for the registry's current approval policy being
340
- * enabled/disabled, this operation's own `requiresApproval` override when set, and the
341
- * effect-derived default otherwise. A real VehicleRegistry.manifest() always sets this
342
- * (false when the registry never called configureApprovals() at all) -- unlike
343
- * `requiresApproval` (the static, author-declared override on the descriptor itself),
344
- * this always reflects the current instant, so a client re-fetching the manifest after a
345
- * live policy change (VehicleRegistry.updateApprovalPolicy) sees the new answer with no
346
- * separate sync mechanism needed.
347
- *
348
- * Optional purely for backward compatibility with every hand-authored VehicleManifest
349
- * test fixture across the ecosystem that predates this field (the same reason
350
- * VehicleManifest.events is optional) -- a consumer reading it should treat undefined the
351
- * same as a caller of classifyVehicleOperationSafety does: fall back to the effect-level
352
- * default, never assume false.
353
- */
354
- readonly approvalRequired?: boolean;
355
- }
356
-
357
- /**
358
- * A named, schema'd event type a provider declares as part of its
359
- * manifest -- the typed alternative to a raw PushChannel.publish(topic,
360
- * payload) call with a hand-invented topic string. Confirmed independently
361
- * reinvented three-plus times across Papyrus and Lector before this
362
- * existed (see this task's own body). No `available` flag the way an
363
- * operation has one: an event type, once declared, is always emittable --
364
- * there's no credential-gated "this event is currently unavailable"
365
- * concept the way a live external-service-backed operation can have.
366
- */
367
- export interface VehicleEventDescriptor {
368
- readonly name: string;
369
- readonly version: number;
370
- readonly description: string;
371
- readonly payloadSchema: JsonSchema;
372
- /** Same bounded-resource discipline as an operation's own maxRequestBytes/maxResponseBytes -- required, never silently defaulted. */
373
- readonly maxPayloadBytes: number;
374
- }
375
-
376
- export interface VehicleEvent<Payload> {
377
- readonly descriptor: VehicleEventDescriptor;
378
- readonly payload: VehicleSchemaCodec<Payload>;
379
- }
380
-
381
- export interface DefineVehicleEventOptions<Payload> {
382
- readonly name: string;
383
- readonly version: number;
384
- readonly description: string;
385
- readonly payload: VehicleSchemaCodec<Payload>;
386
- readonly maxPayloadBytes: number;
387
- }
388
-
389
- function validateEventMetadata<Payload>(options: DefineVehicleEventOptions<Payload>): void {
390
- if (!options.name.trim()) throw new Error("Vehicle event name must not be empty");
391
- if (!Number.isInteger(options.version) || options.version < 1) {
392
- throw new Error("Vehicle event version must be a positive integer");
393
- }
394
- if (!options.description.trim()) throw new Error("Vehicle event description must not be empty");
395
- if (!Number.isSafeInteger(options.maxPayloadBytes) || options.maxPayloadBytes < 1) {
396
- throw new Error("Vehicle event maxPayloadBytes must be a positive integer");
397
- }
398
- }
399
-
400
- export function defineVehicleEvent<Payload>(options: DefineVehicleEventOptions<Payload>): VehicleEvent<Payload> {
401
- validateEventMetadata(options);
402
- const descriptor: VehicleEventDescriptor = Object.freeze({
403
- name: options.name,
404
- version: options.version,
405
- description: options.description,
406
- payloadSchema: cloneJson(options.payload.jsonSchema),
407
- maxPayloadBytes: options.maxPayloadBytes,
408
- });
409
- return Object.freeze({ descriptor, payload: options.payload });
410
- }
411
-
412
- export type VehicleManifestEvent = VehicleEventDescriptor;
413
-
414
- export type VehicleEventHandler<Payload> = (payload: Payload) => void;
415
-
416
- export interface VehicleSubscription {
417
- close(): void;
418
- }
419
-
420
- /**
421
- * The wire topic name a bridge (bridgeVehicleEventsToPushChannel, in
422
- * vehicle-server) publishes an event under, and a subscriber
423
- * (RemoteVehicleClient.subscribe()) subscribes to -- one shared naming
424
- * function in vehicle-core so both sides can never drift apart on the
425
- * convention, the same failure mode this primitive exists to prevent
426
- * providers from reinventing per-project.
427
- */
428
- export function vehicleEventTopic(name: string, version: number): string {
429
- return `vehicle-event:${name}@${version}`;
430
- }
431
-
432
- /**
433
- * `events` is optional purely for backward compatibility with every
434
- * hand-authored VehicleManifest test fixture across the ecosystem that
435
- * predates this field -- a real VehicleRegistry.manifest() always
436
- * populates it (as [] when no events are declared), never omits it.
437
- */
438
- export interface VehicleManifest extends VehicleManifestIdentity {
439
- readonly operations: readonly VehicleManifestOperation[];
440
- readonly events?: readonly VehicleManifestEvent[];
441
- }
442
-
443
- export interface VehicleClient {
444
- manifest(): Promise<VehicleManifest>;
445
- invoke<Output = unknown>(name: string, version: number, input: unknown, options?: VehicleInvocationOptions): Promise<Output>;
446
- close(): Promise<void>;
447
- /**
448
- * Vehicle Jobs -- submit a background-capable operation (one whose descriptor declares
449
- * `background`, see {@link VehicleBackgroundCapability}) and get its jobId back immediately,
450
- * without waiting for the operation itself to make any progress. Optional: a client that
451
- * never talks to a job-capable Vehicle (or a hand-rolled test double) simply omits these five
452
- * methods, exactly like this interface's own long-standing `subscribe()`-shaped extras --
453
- * present on both LocalVehicleClient and RemoteVehicleClient, absent elsewhere. Feature-detect
454
- * via the operation's own manifest `background` capability, not by probing for these methods.
455
- */
456
- submitJob?(name: string, version: number, input: unknown, options?: VehicleJobSubmitOptions): Promise<VehicleJobSubmitResult>;
457
- /** Never blocks -- current status, plus output/error once terminal. */
458
- pollJob?(jobId: string): Promise<VehicleJobSnapshot>;
459
- /** Progress entries strictly after `cursor` (0 for everything so far), plus the next cursor. Never blocks. */
460
- tailJob?(jobId: string, cursor?: number): Promise<VehicleJobTailResult>;
461
- /** Pushes new input to an already-running job's handler, if it opted in via context.steerInputs. */
462
- steerJob?(jobId: string, input: unknown): Promise<void>;
463
- /** Best-effort cancellation of a still-running job -- a no-op against an already-terminal one. */
464
- cancelJob?(jobId: string): Promise<void>;
465
- }
466
-
467
- export function defineVehicleOperation<Input, Output>(
468
- options: DefineVehicleOperationOptions<Input, Output>,
469
- ): VehicleOperation<Input, Output> {
470
- validateOperationMetadata(options);
471
- const descriptor: VehicleOperationDescriptor = Object.freeze({
472
- name: options.name,
473
- version: options.version,
474
- description: options.description,
475
- inputSchema: cloneJson(options.input.jsonSchema),
476
- outputSchema: cloneJson(options.output.jsonSchema),
477
- permissions: Object.freeze([...(options.permissions ?? [])]),
478
- effect: options.effect,
479
- idempotency: Object.freeze({ ...options.idempotency }),
480
- streaming: options.streaming ?? false,
481
- longRunning: options.longRunning ?? false,
482
- limits: Object.freeze({ ...options.limits }),
483
- errors: Object.freeze((options.errors ?? []).map((failure) => Object.freeze({ ...failure }))),
484
- ...(options.requiresApproval !== undefined ? { requiresApproval: options.requiresApproval } : {}),
485
- ...(options.background
486
- ? {
487
- background: Object.freeze({
488
- supported: true as const,
489
- defaultWakeBudget: Object.freeze({ ...options.background.defaultWakeBudget }),
490
- maxWakeBudget: Object.freeze({ ...options.background.maxWakeBudget }),
491
- }),
492
- }
493
- : {}),
494
- });
495
- return Object.freeze({ descriptor, input: options.input, output: options.output });
496
- }
497
-
498
- export function bindVehicleOperation<Input, Output>(
499
- operation: VehicleOperation<Input, Output>,
500
- bind: () => VehicleOperationHandler<Input, Output>,
501
- ): VehicleOperationBinding<Input, Output> {
502
- return Object.freeze({ operation, bind });
503
- }
504
-
505
- function validateOperationMetadata<Input, Output>(options: DefineVehicleOperationOptions<Input, Output>): void {
506
- if (!options.name.trim()) throw new Error("Vehicle operation name must not be empty");
507
- if (!Number.isInteger(options.version) || options.version < 1) {
508
- throw new Error("Vehicle operation version must be a positive integer");
509
- }
510
- if (!options.description.trim()) throw new Error("Vehicle operation description must not be empty");
511
- for (const permission of options.permissions ?? []) {
512
- if (!permission.trim()) throw new Error("Vehicle operation permissions must not contain an empty value");
513
- }
514
- const limits = options.limits;
515
- for (const [name, value] of Object.entries(limits)) {
516
- if (!Number.isSafeInteger(value) || value < 1) throw new Error(`Vehicle operation ${name} must be a positive integer`);
517
- }
518
- if (limits.defaultTimeoutMs > limits.maxTimeoutMs) {
519
- throw new Error("Vehicle operation defaultTimeoutMs must not exceed maxTimeoutMs");
520
- }
521
- if (
522
- options.idempotency.mode === "keyed" &&
523
- (!Number.isSafeInteger(options.idempotency.retentionMs) || options.idempotency.retentionMs < 1)
524
- ) {
525
- throw new Error("Vehicle keyed idempotency retentionMs must be a positive integer");
526
- }
527
- if (options.background) {
528
- if (!options.longRunning) {
529
- throw new Error("Vehicle operation with a background capability must also set longRunning: true");
530
- }
531
- for (const [budgetName, budget] of [
532
- ["defaultWakeBudget", options.background.defaultWakeBudget],
533
- ["maxWakeBudget", options.background.maxWakeBudget],
534
- ] as const) {
535
- if (!Number.isSafeInteger(budget.maxCount) || budget.maxCount < 1) {
536
- throw new Error(`Vehicle operation background.${budgetName}.maxCount must be a positive integer`);
537
- }
538
- if (!Number.isSafeInteger(budget.maxBytes) || budget.maxBytes < 1) {
539
- throw new Error(`Vehicle operation background.${budgetName}.maxBytes must be a positive integer`);
540
- }
541
- }
542
- if (options.background.defaultWakeBudget.maxCount > options.background.maxWakeBudget.maxCount) {
543
- throw new Error("Vehicle operation background.defaultWakeBudget.maxCount must not exceed maxWakeBudget.maxCount");
544
- }
545
- if (options.background.defaultWakeBudget.maxBytes > options.background.maxWakeBudget.maxBytes) {
546
- throw new Error("Vehicle operation background.defaultWakeBudget.maxBytes must not exceed maxWakeBudget.maxBytes");
547
- }
548
- }
549
- }
550
-
551
- function cloneJson<T extends JsonValue>(value: T): T {
552
- const serialized = JSON.stringify(value);
553
- if (serialized === undefined) throw new Error("Vehicle JSON metadata must be serializable");
554
- return freezeJson(JSON.parse(serialized) as JsonValue) as T;
555
- }
556
-
557
- function freezeJson(value: JsonValue): JsonValue {
558
- if (Array.isArray(value)) return Object.freeze(value.map(freezeJson));
559
- if (value !== null && typeof value === "object") {
560
- return Object.freeze(Object.fromEntries(Object.entries(value).map(([key, child]) => [key, freezeJson(child)])));
561
- }
562
- return value;
563
- }