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