@danypops/vehicle-core 0.17.0 → 0.18.0

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