@vite-hub/runtime 0.0.1 → 0.0.3

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.
package/README.md CHANGED
@@ -26,7 +26,7 @@ import {
26
26
  } from "@vite-hub/runtime"
27
27
 
28
28
  const context = createExecutionContext({
29
- runtime: "nitro",
29
+ runtime: "vite",
30
30
  memo: (key, create) => create(),
31
31
  waitUntil: task => task.catch(() => {}),
32
32
  capabilities: {
@@ -44,6 +44,18 @@ const decision = await resolveCapabilityPolicy("require-approval", {
44
44
  })
45
45
  ```
46
46
 
47
+ An omitted policy resolves to `allow`. Pass `require-approval` or `deny` when an operation needs an explicit gate.
48
+
49
+ ## Execution authority
50
+
51
+ `ExecutionAuthority` is the normalized, provider-independent description of what one resolved execution surface grants. It records filesystem access and scope, network egress, environment inheritance, credential access, process execution, and the isolation mechanism. Read it from the resolved owner, such as `box.plan.executionAuthority`, `WorkspaceSession.executionAuthority`, `SandboxRunner.executionAuthority`, or `AgentInspectionMetadata.config.driver.executionAuthority`.
52
+
53
+ Each resolved descriptor is an immutable snapshot of the authority known at resolution time. `unknown` means the provider cannot prove or did not report that dimension; it never means `none`. `isolation` identifies a mechanism such as a container or microVM, but it is not a security rank and does not imply anything about filesystem, network, credentials, or processes. Providers must report every dimension explicitly instead of inheriting a permissive default.
54
+
55
+ Executable selection, fixed argument arrays, and executable allowlists are dispatch controls. They do not constrain what a selected process can read, reach, inherit, or spawn, so they are not represented as isolation.
56
+
57
+ `ViteHubError` clones and freezes its JSON-safe public details at construction, and `toJSON()` always returns that immutable snapshot. Put raw provider failures in `cause`; changing the original details or the error's public fields later cannot change serialized output. Accessors, cycles, `bigint`, non-finite numbers, and oversized detail trees are rejected with a fixed `TypeError`, so callers that previously passed mutable or non-JSON detail objects must normalize them first.
58
+
47
59
  ## Used by
48
60
 
49
61
  Feature packages use Runtime Capability handles instead of passing every provider client through every API. Agent Capabilities consume these handles when they expose KV, Blob, DB, sandbox, shell, or workspace behavior.
package/dist/index.d.ts CHANGED
@@ -1,5 +1,46 @@
1
+ //#region src/errors.d.ts
2
+ type ViteHubErrorDetail = boolean | null | number | string | readonly ViteHubErrorDetail[] | {
3
+ readonly [key: string]: ViteHubErrorDetail | undefined;
4
+ };
5
+ type ViteHubErrorDetails = Readonly<Record<string, ViteHubErrorDetail | undefined>>;
6
+ interface ViteHubErrorShape<TCode extends string = string, TDetails extends ViteHubErrorDetails = ViteHubErrorDetails> {
7
+ code: TCode;
8
+ details?: TDetails;
9
+ message: string;
10
+ name: "ViteHubError";
11
+ requestId?: string;
12
+ }
13
+ interface ViteHubErrorOptions<TDetails extends ViteHubErrorDetails = ViteHubErrorDetails> extends ErrorOptions {
14
+ details?: TDetails;
15
+ requestId?: string;
16
+ }
17
+ declare class ViteHubError<TCode extends string = string, TDetails extends ViteHubErrorDetails = ViteHubErrorDetails> extends Error {
18
+ readonly code: TCode;
19
+ readonly details?: TDetails;
20
+ readonly requestId?: string;
21
+ constructor(code: TCode, message: string, options?: ViteHubErrorOptions<TDetails>);
22
+ toJSON(): ViteHubErrorShape<TCode, TDetails>;
23
+ }
24
+ declare function getViteHubErrorShape(value: unknown): ViteHubErrorShape | undefined;
25
+ declare function isViteHubError(value: unknown): value is ViteHubErrorShape;
26
+ //#endregion
1
27
  //#region src/index.d.ts
2
28
  type MaybePromise<T> = T | Promise<T>;
29
+ interface ExecutionAuthority {
30
+ readonly credentials: "ambient" | "none" | "provisioned" | "unknown";
31
+ readonly environment: "ambient" | "none" | "selected" | "unknown";
32
+ readonly filesystem: {
33
+ readonly access: "none" | "read-only" | "read-write" | "unknown";
34
+ readonly scope: "host" | "none" | "sandbox" | "unknown" | "workspace";
35
+ };
36
+ readonly isolation: "container" | "microvm" | "none" | "process" | "unknown";
37
+ readonly network: "none" | "restricted" | "unrestricted" | "unknown";
38
+ readonly processes: "arbitrary" | "none" | "restricted" | "unknown";
39
+ }
40
+ declare const noExecutionAuthority: ExecutionAuthority;
41
+ declare const unknownExecutionAuthority: ExecutionAuthority;
42
+ declare function isExecutionAuthority(value: unknown): value is ExecutionAuthority;
43
+ declare function normalizeExecutionAuthority(value: unknown): ExecutionAuthority;
3
44
  type RuntimeWaitUntil = (task: Promise<unknown>) => void;
4
45
  interface RuntimeWaitUntilController {
5
46
  flushWaitUntil(): Promise<void>;
@@ -10,6 +51,9 @@ interface TraceContext {
10
51
  parentId?: string;
11
52
  sampled?: boolean;
12
53
  }
54
+ type TraceEventContentPolicy = "content" | "metadata";
55
+ type TraceRunStatus = "completed" | "failed" | "running";
56
+ type TraceStepStatus = "completed" | "failed" | "running";
13
57
  interface TraceEvent {
14
58
  attributes?: Record<string, unknown>;
15
59
  name: string;
@@ -17,6 +61,51 @@ interface TraceEvent {
17
61
  trace?: TraceContext;
18
62
  type: "approval" | "capability" | "error" | "lifecycle" | "policy" | "run";
19
63
  }
64
+ interface TraceEventLogEntry extends TraceEvent {
65
+ sequence: number;
66
+ timestamp: string;
67
+ }
68
+ interface TraceEventLog {
69
+ append(event: TraceEvent): MaybePromise<TraceEventLogEntry>;
70
+ entries(): readonly TraceEventLogEntry[];
71
+ }
72
+ interface TraceEventLogOptions {
73
+ content?: TraceEventContentPolicy;
74
+ onEntry?: (entry: TraceEventLogEntry) => MaybePromise<void>;
75
+ }
76
+ interface TraceStepView {
77
+ attributes?: Record<string, unknown>;
78
+ durationMs?: number;
79
+ endTime?: string;
80
+ events: TraceEventLogEntry[];
81
+ id: string;
82
+ name: string;
83
+ startTime: string;
84
+ status: TraceStepStatus;
85
+ type: TraceEvent["type"];
86
+ }
87
+ interface TraceRunView {
88
+ durationMs?: number;
89
+ endTime?: string;
90
+ events: TraceEventLogEntry[];
91
+ id: string;
92
+ startTime: string;
93
+ status: TraceRunStatus;
94
+ steps: TraceStepView[];
95
+ }
96
+ interface OpenTelemetrySpanView {
97
+ attributes?: Record<string, unknown>;
98
+ endTime?: string;
99
+ name: string;
100
+ parentSpanId?: string;
101
+ spanId: string;
102
+ startTime: string;
103
+ status: {
104
+ code: "ERROR" | "OK";
105
+ message?: string;
106
+ };
107
+ traceId: string;
108
+ }
20
109
  interface RuntimeHostContext<TRuntimeConfig = Record<string, unknown>> {
21
110
  capabilities?: RuntimeCapabilities;
22
111
  cloudflare?: {
@@ -31,6 +120,7 @@ interface RuntimeHostContext<TRuntimeConfig = Record<string, unknown>> {
31
120
  runtime: string;
32
121
  runtimeConfig?: TRuntimeConfig;
33
122
  trace?: TraceContext;
123
+ traceLog?: TraceEventLog;
34
124
  vercel?: {
35
125
  waitUntil?: RuntimeWaitUntil;
36
126
  };
@@ -89,6 +179,10 @@ interface RunLifecycleHooks<TContext extends RuntimeHostContext<any> = RuntimeHo
89
179
  request?: (context: TContext) => MaybePromise<void>;
90
180
  trace?: (event: TraceEvent, context: TContext) => MaybePromise<void>;
91
181
  }
182
+ declare function emitTraceEvent<TContext extends RuntimeHostContext<any>>(context: TContext, event: TraceEvent): Promise<TraceEventLogEntry | undefined>;
183
+ declare function createTraceEventLog(options?: TraceEventLogOptions): TraceEventLog;
184
+ declare function deriveTraceRuns(events: Iterable<TraceEventLogEntry>): TraceRunView[];
185
+ declare function traceEventsToOpenTelemetrySpans(events: Iterable<TraceEventLogEntry>): OpenTelemetrySpanView[];
92
186
  interface Lease {
93
187
  expiresAt?: Date | string;
94
188
  id: string;
@@ -101,16 +195,6 @@ interface LeaseStore {
101
195
  ttl?: number;
102
196
  }): MaybePromise<Lease>;
103
197
  }
104
- declare class CapabilityNotFoundError extends Error {
105
- constructor(name: string);
106
- }
107
- declare class CapabilityDeniedError extends Error {
108
- constructor(name: string, reason?: string);
109
- }
110
- declare class ApprovalRequiredError<TInput = unknown> extends Error {
111
- request: ApprovalRequest<TInput>;
112
- constructor(request: ApprovalRequest<TInput>);
113
- }
114
198
  declare function createExecutionContext<TRuntimeConfig = Record<string, unknown>, TContext extends RuntimeHostContext<TRuntimeConfig> = RuntimeHostContext<TRuntimeConfig>>(context: TContext): TContext & ExecutionContext<TRuntimeConfig>;
115
199
  declare function resolveExecutionContext<TRuntimeConfig = Record<string, unknown>, TContext extends RuntimeHostContext<TRuntimeConfig> = RuntimeHostContext<TRuntimeConfig>>(context: TContext): TContext & ExecutionContext<TRuntimeConfig>;
116
200
  declare function resolveRuntimeContext<TRuntimeConfig = Record<string, unknown>, TContext extends RuntimeHostContext<TRuntimeConfig> = RuntimeHostContext<TRuntimeConfig>>(context: TContext): TContext & ExecutionContext<TRuntimeConfig>;
@@ -126,4 +210,4 @@ declare function isResolvable<T, TContext extends RuntimeHostContext<any>>(value
126
210
  declare function resolveRuntimeValue<T, TContext extends RuntimeHostContext<any>>(value: MaybeResolvable<T, TContext>, context: TContext): Promise<T>;
127
211
  declare function resolveCapabilityPolicy(policy: CapabilityPolicy | undefined, context: PolicyContext): Promise<PolicyDecision>;
128
212
  //#endregion
129
- export { ApprovalDecision, ApprovalRequest, ApprovalRequiredError, ApprovalState, CapabilityDefinition, CapabilityDeniedError, CapabilityHandle, CapabilityNotFoundError, CapabilityPolicy, ExecutionContext, Lease, LeaseStore, MaybePromise, MaybeResolvable, PolicyContext, PolicyDecision, Resolvable, ResolvedRuntimeHostContext, RunLifecycleHooks, RuntimeCapabilities, RuntimeCapabilityHandle, RuntimeHostContext, RuntimeWaitUntil, RuntimeWaitUntilController, TraceContext, TraceEvent, createExecutionContext, createRuntimeWaitUntilController, defineCapability, getCapability, hasCapability, isResolvable, resolveCapabilityPolicy, resolveExecutionContext, resolveRuntimeContext, resolveRuntimeValue };
213
+ export { ApprovalDecision, ApprovalRequest, ApprovalState, CapabilityDefinition, CapabilityHandle, CapabilityPolicy, ExecutionAuthority, ExecutionContext, Lease, LeaseStore, MaybePromise, MaybeResolvable, OpenTelemetrySpanView, PolicyContext, PolicyDecision, Resolvable, ResolvedRuntimeHostContext, RunLifecycleHooks, RuntimeCapabilities, RuntimeCapabilityHandle, RuntimeHostContext, RuntimeWaitUntil, RuntimeWaitUntilController, TraceContext, TraceEvent, TraceEventContentPolicy, TraceEventLog, TraceEventLogEntry, TraceEventLogOptions, TraceRunStatus, TraceRunView, TraceStepStatus, TraceStepView, ViteHubError, type ViteHubErrorDetail, type ViteHubErrorDetails, type ViteHubErrorOptions, type ViteHubErrorShape, createExecutionContext, createRuntimeWaitUntilController, createTraceEventLog, defineCapability, deriveTraceRuns, emitTraceEvent, getCapability, getViteHubErrorShape, hasCapability, isExecutionAuthority, isResolvable, isViteHubError, noExecutionAuthority, normalizeExecutionAuthority, resolveCapabilityPolicy, resolveExecutionContext, resolveRuntimeContext, resolveRuntimeValue, traceEventsToOpenTelemetrySpans, unknownExecutionAuthority };
package/dist/index.js CHANGED
@@ -1,24 +1,518 @@
1
- //#region src/index.ts
2
- var CapabilityNotFoundError = class extends Error {
3
- constructor(name) {
4
- super(`[vitehub:runtime] Capability "${name}" was not found.`);
5
- this.name = "CapabilityNotFoundError";
1
+ //#region src/errors.ts
2
+ const MAX_DETAIL_DEPTH = 8;
3
+ const MAX_DETAIL_ENTRIES = 128;
4
+ const MAX_DETAIL_KEY_LENGTH = 128;
5
+ const MAX_DETAIL_NODES = 1024;
6
+ const MAX_DETAIL_STRING_LENGTH = 16384;
7
+ const MAX_ERROR_CODE_LENGTH = 128;
8
+ const MAX_ERROR_MESSAGE_LENGTH = 16384;
9
+ const MAX_REQUEST_ID_LENGTH = 256;
10
+ const publicShapes = /* @__PURE__ */ new WeakMap();
11
+ function invalidPublicError() {
12
+ throw new TypeError("[vitehub] ViteHubError requires a valid public error contract.");
13
+ }
14
+ function isArray(value) {
15
+ try {
16
+ return Array.isArray(value);
17
+ } catch {
18
+ invalidPublicError();
6
19
  }
7
- };
8
- var CapabilityDeniedError = class extends Error {
9
- constructor(name, reason) {
10
- super(`[vitehub:runtime] Capability "${name}" was denied${reason ? `: ${reason}` : "."}`);
11
- this.name = "CapabilityDeniedError";
20
+ }
21
+ function readOwnDataProperty(value, key, requireEnumerable = false) {
22
+ try {
23
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
24
+ if (descriptor === void 0) return void 0;
25
+ if (!("value" in descriptor) || requireEnumerable && !descriptor.enumerable) invalidPublicError();
26
+ return descriptor.value;
27
+ } catch {
28
+ invalidPublicError();
12
29
  }
13
- };
14
- var ApprovalRequiredError = class extends Error {
15
- request;
16
- constructor(request) {
17
- super(`[vitehub:runtime] Approval is required for "${request.capability || request.id}".`);
18
- this.name = "ApprovalRequiredError";
19
- this.request = request;
30
+ }
31
+ function clonePublicDetail(value, state, depth, allowUndefined) {
32
+ state.nodes += 1;
33
+ if (state.nodes > MAX_DETAIL_NODES) invalidPublicError();
34
+ if (value === void 0 && allowUndefined) return void 0;
35
+ if (value === null || typeof value === "boolean") return value;
36
+ if (typeof value === "string" && value.length <= MAX_DETAIL_STRING_LENGTH) return value;
37
+ if (typeof value === "number" && Number.isFinite(value)) return value;
38
+ if (typeof value !== "object" || depth > MAX_DETAIL_DEPTH || state.ancestors.has(value)) invalidPublicError();
39
+ let prototype;
40
+ let keys;
41
+ try {
42
+ prototype = Object.getPrototypeOf(value);
43
+ keys = Reflect.ownKeys(value);
44
+ } catch {
45
+ invalidPublicError();
46
+ }
47
+ state.ancestors.add(value);
48
+ try {
49
+ if (isArray(value)) {
50
+ const length = readOwnDataProperty(value, "length");
51
+ if (!Number.isSafeInteger(length) || length < 0 || length > MAX_DETAIL_ENTRIES || keys.length !== length + 1 || !keys.includes("length")) invalidPublicError();
52
+ const result = [];
53
+ for (let index = 0; index < length; index += 1) {
54
+ const key = String(index);
55
+ if (!keys.includes(key)) invalidPublicError();
56
+ result.push(clonePublicDetail(readOwnDataProperty(value, key, true), state, depth + 1, false));
57
+ }
58
+ return Object.freeze(result);
59
+ }
60
+ if (prototype !== Object.prototype && prototype !== null) invalidPublicError();
61
+ if (keys.length > MAX_DETAIL_ENTRIES || keys.some((key) => typeof key !== "string")) invalidPublicError();
62
+ const result = {};
63
+ for (const key of keys) {
64
+ if (key.length === 0 || key.length > MAX_DETAIL_KEY_LENGTH) invalidPublicError();
65
+ Object.defineProperty(result, key, {
66
+ enumerable: true,
67
+ value: clonePublicDetail(readOwnDataProperty(value, key, true), state, depth + 1, true),
68
+ writable: true
69
+ });
70
+ }
71
+ return Object.freeze(result);
72
+ } finally {
73
+ state.ancestors.delete(value);
74
+ }
75
+ }
76
+ function clonePublicDetails(value) {
77
+ if (value === void 0) return void 0;
78
+ if (typeof value !== "object" || value === null || isArray(value)) invalidPublicError();
79
+ return clonePublicDetail(value, {
80
+ ancestors: /* @__PURE__ */ new Set(),
81
+ nodes: 0
82
+ }, 0, false);
83
+ }
84
+ function normalizePublicError(code, message, options) {
85
+ if (typeof code !== "string" || code.length === 0 || code.length > MAX_ERROR_CODE_LENGTH) invalidPublicError();
86
+ if (typeof message !== "string" || message.length === 0 || message.length > MAX_ERROR_MESSAGE_LENGTH) invalidPublicError();
87
+ if (typeof options !== "object" || options === null || isArray(options)) invalidPublicError();
88
+ const cause = readOwnDataProperty(options, "cause");
89
+ const details = clonePublicDetails(readOwnDataProperty(options, "details"));
90
+ const requestId = readOwnDataProperty(options, "requestId");
91
+ if (requestId !== void 0 && (typeof requestId !== "string" || requestId.length === 0 || requestId.length > MAX_REQUEST_ID_LENGTH)) invalidPublicError();
92
+ return {
93
+ cause,
94
+ code,
95
+ details,
96
+ message,
97
+ name: "ViteHubError",
98
+ requestId,
99
+ shape: Object.freeze({
100
+ code,
101
+ ...details === void 0 ? {} : { details },
102
+ message,
103
+ name: "ViteHubError",
104
+ ...requestId === void 0 ? {} : { requestId }
105
+ })
106
+ };
107
+ }
108
+ var ViteHubError = class extends Error {
109
+ code;
110
+ details;
111
+ requestId;
112
+ constructor(code, message, options = {}) {
113
+ const normalized = normalizePublicError(code, message, options);
114
+ super(normalized.message, normalized.cause === void 0 ? void 0 : { cause: normalized.cause });
115
+ this.name = "ViteHubError";
116
+ this.code = normalized.code;
117
+ this.details = normalized.details;
118
+ this.requestId = normalized.requestId;
119
+ const toJSON = this.toJSON.bind(this);
120
+ Object.defineProperties(this, {
121
+ code: {
122
+ configurable: true,
123
+ enumerable: true,
124
+ value: normalized.code,
125
+ writable: false
126
+ },
127
+ details: {
128
+ configurable: true,
129
+ enumerable: true,
130
+ value: normalized.details,
131
+ writable: false
132
+ },
133
+ message: {
134
+ configurable: true,
135
+ enumerable: false,
136
+ value: normalized.message,
137
+ writable: false
138
+ },
139
+ name: {
140
+ configurable: false,
141
+ enumerable: false,
142
+ value: normalized.name,
143
+ writable: false
144
+ },
145
+ requestId: {
146
+ configurable: true,
147
+ enumerable: true,
148
+ value: normalized.requestId,
149
+ writable: false
150
+ },
151
+ toJSON: {
152
+ configurable: false,
153
+ enumerable: false,
154
+ value: toJSON,
155
+ writable: false
156
+ }
157
+ });
158
+ publicShapes.set(this, normalized.shape);
159
+ }
160
+ toJSON() {
161
+ const existing = publicShapes.get(this);
162
+ if (existing) return existing;
163
+ const normalized = normalizePublicError(readOwnDataProperty(this, "code"), readOwnDataProperty(this, "message"), {
164
+ details: readOwnDataProperty(this, "details"),
165
+ requestId: readOwnDataProperty(this, "requestId")
166
+ });
167
+ publicShapes.set(this, normalized.shape);
168
+ return normalized.shape;
20
169
  }
21
170
  };
171
+ function getViteHubErrorShape(value) {
172
+ if (typeof value !== "object" || value === null) return;
173
+ try {
174
+ const existing = publicShapes.get(value);
175
+ if (existing) return existing;
176
+ if (readOwnDataProperty(value, "name") !== "ViteHubError") return;
177
+ return normalizePublicError(readOwnDataProperty(value, "code"), readOwnDataProperty(value, "message"), {
178
+ details: readOwnDataProperty(value, "details"),
179
+ requestId: readOwnDataProperty(value, "requestId")
180
+ }).shape;
181
+ } catch {
182
+ return;
183
+ }
184
+ }
185
+ function isViteHubError(value) {
186
+ return getViteHubErrorShape(value) !== void 0;
187
+ }
188
+ //#endregion
189
+ //#region src/index.ts
190
+ const noExecutionAuthority = Object.freeze({
191
+ credentials: "none",
192
+ environment: "none",
193
+ filesystem: Object.freeze({
194
+ access: "none",
195
+ scope: "none"
196
+ }),
197
+ isolation: "none",
198
+ network: "none",
199
+ processes: "none"
200
+ });
201
+ const unknownExecutionAuthority = Object.freeze({
202
+ credentials: "unknown",
203
+ environment: "unknown",
204
+ filesystem: Object.freeze({
205
+ access: "unknown",
206
+ scope: "unknown"
207
+ }),
208
+ isolation: "unknown",
209
+ network: "unknown",
210
+ processes: "unknown"
211
+ });
212
+ function isExecutionAuthority(value) {
213
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
214
+ const authority = value;
215
+ const filesystem = authority.filesystem;
216
+ if (!filesystem || typeof filesystem !== "object" || Array.isArray(filesystem)) return false;
217
+ const files = filesystem;
218
+ return typeof authority.credentials === "string" && [
219
+ "ambient",
220
+ "none",
221
+ "provisioned",
222
+ "unknown"
223
+ ].includes(authority.credentials) && typeof authority.environment === "string" && [
224
+ "ambient",
225
+ "none",
226
+ "selected",
227
+ "unknown"
228
+ ].includes(authority.environment) && typeof files.access === "string" && [
229
+ "none",
230
+ "read-only",
231
+ "read-write",
232
+ "unknown"
233
+ ].includes(files.access) && typeof files.scope === "string" && [
234
+ "host",
235
+ "none",
236
+ "sandbox",
237
+ "unknown",
238
+ "workspace"
239
+ ].includes(files.scope) && typeof authority.isolation === "string" && [
240
+ "container",
241
+ "microvm",
242
+ "none",
243
+ "process",
244
+ "unknown"
245
+ ].includes(authority.isolation) && typeof authority.network === "string" && [
246
+ "none",
247
+ "restricted",
248
+ "unrestricted",
249
+ "unknown"
250
+ ].includes(authority.network) && typeof authority.processes === "string" && [
251
+ "arbitrary",
252
+ "none",
253
+ "restricted",
254
+ "unknown"
255
+ ].includes(authority.processes);
256
+ }
257
+ function normalizeExecutionAuthority(value) {
258
+ if (!isExecutionAuthority(value)) throw new TypeError("[vitehub] Invalid execution authority descriptor.");
259
+ if (hasCanonicalFrozenProperties(value, [
260
+ "credentials",
261
+ "environment",
262
+ "filesystem",
263
+ "isolation",
264
+ "network",
265
+ "processes"
266
+ ]) && hasCanonicalFrozenProperties(value.filesystem, ["access", "scope"])) return value;
267
+ return Object.freeze({
268
+ credentials: value.credentials,
269
+ environment: value.environment,
270
+ filesystem: Object.freeze({
271
+ access: value.filesystem.access,
272
+ scope: value.filesystem.scope
273
+ }),
274
+ isolation: value.isolation,
275
+ network: value.network,
276
+ processes: value.processes
277
+ });
278
+ }
279
+ function hasCanonicalFrozenProperties(value, keys) {
280
+ const prototype = Object.getPrototypeOf(value);
281
+ if (!Object.isFrozen(value) || prototype !== Object.prototype && prototype !== null) return false;
282
+ const ownKeys = Reflect.ownKeys(value);
283
+ if (ownKeys.length !== keys.length || ownKeys.some((key) => typeof key !== "string" || !keys.includes(key))) return false;
284
+ return keys.every((key) => {
285
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
286
+ return descriptor !== void 0 && "value" in descriptor && descriptor.enumerable;
287
+ });
288
+ }
289
+ const contentAttributeKeys = new Set([
290
+ "args",
291
+ "body",
292
+ "content",
293
+ "data",
294
+ "input",
295
+ "message",
296
+ "messages",
297
+ "output",
298
+ "payload",
299
+ "prompt",
300
+ "raw",
301
+ "request",
302
+ "response",
303
+ "result",
304
+ "text"
305
+ ]);
306
+ function isContentAttributeKey(key) {
307
+ if (key === "error.message") return false;
308
+ if (contentAttributeKeys.has(key)) return true;
309
+ return key.split(".").some((part, index) => index > 0 && contentAttributeKeys.has(part));
310
+ }
311
+ function isPlainRecord(value) {
312
+ return Boolean(value && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype);
313
+ }
314
+ function metadataValue(value) {
315
+ if (Array.isArray(value)) return value.map(metadataValue);
316
+ if (!isPlainRecord(value)) return value;
317
+ const omitted = [];
318
+ const next = Object.fromEntries(Object.entries(value).flatMap(([key, child]) => {
319
+ if (isContentAttributeKey(key)) {
320
+ omitted.push(key);
321
+ return [];
322
+ }
323
+ return [[key, metadataValue(child)]];
324
+ }));
325
+ if (omitted.length) next["content.omitted"] = omitted;
326
+ return next;
327
+ }
328
+ function timestamp(value) {
329
+ if (value instanceof Date) return value.toISOString();
330
+ if (typeof value === "string") return value;
331
+ return (/* @__PURE__ */ new Date()).toISOString();
332
+ }
333
+ function metadataAttributes(attributes) {
334
+ if (!attributes) return void 0;
335
+ const omitted = [];
336
+ const next = Object.fromEntries(Object.entries(attributes).flatMap(([key, value]) => {
337
+ if (isContentAttributeKey(key)) {
338
+ omitted.push(key);
339
+ return [];
340
+ }
341
+ return [[key, metadataValue(value)]];
342
+ }));
343
+ if (omitted.length) next["content.omitted"] = omitted;
344
+ return Object.keys(next).length ? next : void 0;
345
+ }
346
+ function normalizeTraceEvent(event, sequence, content) {
347
+ return {
348
+ ...event,
349
+ ...content === "metadata" ? { attributes: metadataAttributes(event.attributes) } : {},
350
+ sequence,
351
+ timestamp: timestamp(event.timestamp)
352
+ };
353
+ }
354
+ async function emitTraceEvent(context, event) {
355
+ return await context.traceLog?.append({
356
+ ...event,
357
+ trace: event.trace || context.trace
358
+ });
359
+ }
360
+ function createTraceEventLog(options = {}) {
361
+ const content = options.content || "metadata";
362
+ const entries = [];
363
+ return {
364
+ async append(event) {
365
+ const entry = normalizeTraceEvent(event, entries.length + 1, content);
366
+ entries.push(entry);
367
+ await options.onEntry?.(entry);
368
+ return entry;
369
+ },
370
+ entries() {
371
+ return entries.slice();
372
+ }
373
+ };
374
+ }
375
+ function millis(value) {
376
+ const parsed = Date.parse(value);
377
+ return Number.isFinite(parsed) ? parsed : 0;
378
+ }
379
+ function durationMs(startTime, endTime) {
380
+ if (!endTime) return void 0;
381
+ const duration = millis(endTime) - millis(startTime);
382
+ return Number.isFinite(duration) && duration >= 0 ? duration : void 0;
383
+ }
384
+ function firstString(...values) {
385
+ return values.find((value) => typeof value === "string" && value.length > 0);
386
+ }
387
+ function runId(event) {
388
+ return firstString(event.attributes?.["agent.run.id"], event.attributes?.["run.id"], event.attributes?.runId, event.trace?.id) || "default";
389
+ }
390
+ function stepId(event) {
391
+ return firstString(event.attributes?.["step.id"], event.attributes?.["tool.id"], event.attributes?.["approval.id"], event.attributes?.["model.call.id"]);
392
+ }
393
+ function stepStatus(event) {
394
+ return event.type === "error" || event.name.endsWith(".error") ? "failed" : event.name.endsWith(".start") || event.name.endsWith(".request") ? "running" : "completed";
395
+ }
396
+ function isTraceRunFinish(event) {
397
+ return event.name === "agent.invocation.finish" || event.name === "run.finish";
398
+ }
399
+ function isTraceRunError(event) {
400
+ return event.name === "agent.invocation.error" || event.name === "agent.stream.error" || event.name === "run.error";
401
+ }
402
+ function deriveTraceRuns(events) {
403
+ const groups = /* @__PURE__ */ new Map();
404
+ for (const event of events) {
405
+ const id = runId(event);
406
+ groups.set(id, [...groups.get(id) || [], event]);
407
+ }
408
+ return [...groups.entries()].map(([id, group]) => {
409
+ const sorted = group.slice().sort((a, b) => a.sequence - b.sequence);
410
+ const first = sorted[0];
411
+ const steps = /* @__PURE__ */ new Map();
412
+ for (const event of sorted) {
413
+ const id = stepId(event);
414
+ if (!id) continue;
415
+ const existing = steps.get(id);
416
+ const status = stepStatus(event);
417
+ if (!existing) {
418
+ steps.set(id, {
419
+ attributes: event.attributes,
420
+ endTime: status === "running" ? void 0 : event.timestamp,
421
+ events: [event],
422
+ id,
423
+ name: event.name.replace(/\.(start|finish|end|error|request|decision|recorded)$/, ""),
424
+ startTime: event.timestamp,
425
+ status,
426
+ type: event.type
427
+ });
428
+ continue;
429
+ }
430
+ existing.events.push(event);
431
+ existing.attributes = {
432
+ ...existing.attributes,
433
+ ...event.attributes
434
+ };
435
+ if (status !== "running") {
436
+ existing.endTime = event.timestamp;
437
+ existing.status = status;
438
+ existing.durationMs = durationMs(existing.startTime, existing.endTime);
439
+ }
440
+ }
441
+ const terminal = sorted.slice().reverse().find((event) => isTraceRunError(event) || isTraceRunFinish(event));
442
+ const status = sorted.some(isTraceRunError) ? "failed" : terminal ? "completed" : "running";
443
+ const endTime = status === "running" ? void 0 : terminal?.timestamp;
444
+ return {
445
+ durationMs: durationMs(first.timestamp, endTime),
446
+ endTime,
447
+ events: sorted,
448
+ id,
449
+ startTime: first.timestamp,
450
+ status,
451
+ steps: [...steps.values()]
452
+ };
453
+ });
454
+ }
455
+ function traceRunTraceId(run) {
456
+ return firstString(...run.events.map((event) => event.trace?.id), run.id) || run.id;
457
+ }
458
+ function traceRunParentId(run) {
459
+ return firstString(...run.events.map((event) => event.trace?.parentId));
460
+ }
461
+ function isOpenTelemetryId(value, length) {
462
+ return value.length === length && /^[0-9a-f]+$/.test(value);
463
+ }
464
+ function openTelemetryId(value, length) {
465
+ const normalized = value.toLowerCase();
466
+ if (isOpenTelemetryId(normalized, length)) return normalized;
467
+ let output = "";
468
+ for (let seed = 0; output.length < length; seed += 1) {
469
+ let hash = 2166136261;
470
+ const input = `${value}:${seed}`;
471
+ for (let index = 0; index < input.length; index += 1) {
472
+ hash ^= input.charCodeAt(index);
473
+ hash = Math.imul(hash, 16777619);
474
+ }
475
+ output += (hash >>> 0).toString(16).padStart(8, "0");
476
+ }
477
+ const id = output.slice(0, length);
478
+ return /^0+$/.test(id) ? `1${id.slice(1)}` : id;
479
+ }
480
+ function traceEventsToOpenTelemetrySpans(events) {
481
+ return deriveTraceRuns(events).flatMap((run) => {
482
+ const rawParentSpanId = traceRunParentId(run);
483
+ const rawTraceId = traceRunTraceId(run);
484
+ const parentSpanId = rawParentSpanId ? openTelemetryId(rawParentSpanId, 16) : void 0;
485
+ const spanId = openTelemetryId(run.id, 16);
486
+ const traceId = openTelemetryId(rawTraceId, 32);
487
+ return [{
488
+ attributes: {
489
+ "vitehub.run.id": run.id,
490
+ ...rawParentSpanId ? { "vitehub.trace.parentId": rawParentSpanId } : {},
491
+ "vitehub.trace.id": rawTraceId
492
+ },
493
+ endTime: run.endTime,
494
+ name: "vitehub.run",
495
+ ...parentSpanId ? { parentSpanId } : {},
496
+ spanId,
497
+ startTime: run.startTime,
498
+ status: { code: run.status === "failed" ? "ERROR" : "OK" },
499
+ traceId
500
+ }, ...run.steps.map((step) => ({
501
+ attributes: {
502
+ ...step.attributes,
503
+ "vitehub.run.id": run.id,
504
+ "vitehub.step.id": step.id
505
+ },
506
+ endTime: step.endTime,
507
+ name: step.name,
508
+ parentSpanId: spanId,
509
+ spanId: openTelemetryId(`${run.id}:${step.id}`, 16),
510
+ startTime: step.startTime,
511
+ status: { code: step.status === "failed" ? "ERROR" : "OK" },
512
+ traceId
513
+ }))];
514
+ });
515
+ }
22
516
  function createExecutionContext(context) {
23
517
  return resolveExecutionContext(context);
24
518
  }
@@ -62,7 +556,7 @@ function hasCapability(context, name) {
62
556
  }
63
557
  function getCapability(context, name) {
64
558
  const value = context.capabilities?.[name];
65
- if (value === void 0) throw new CapabilityNotFoundError(name);
559
+ if (value === void 0) throw new ViteHubError("CAPABILITY_NOT_FOUND", `[vitehub:runtime] Capability "${name}" was not found.`, { details: { capability: name } });
66
560
  if (isCapabilityHandle(value)) return value;
67
561
  return defineCapability(name, value, { name });
68
562
  }
@@ -79,4 +573,4 @@ async function resolveCapabilityPolicy(policy, context) {
79
573
  return typeof policy === "function" ? await policy(context) : policy;
80
574
  }
81
575
  //#endregion
82
- export { ApprovalRequiredError, CapabilityDeniedError, CapabilityNotFoundError, createExecutionContext, createRuntimeWaitUntilController, defineCapability, getCapability, hasCapability, isResolvable, resolveCapabilityPolicy, resolveExecutionContext, resolveRuntimeContext, resolveRuntimeValue };
576
+ export { ViteHubError, createExecutionContext, createRuntimeWaitUntilController, createTraceEventLog, defineCapability, deriveTraceRuns, emitTraceEvent, getCapability, getViteHubErrorShape, hasCapability, isExecutionAuthority, isResolvable, isViteHubError, noExecutionAuthority, normalizeExecutionAuthority, resolveCapabilityPolicy, resolveExecutionContext, resolveRuntimeContext, resolveRuntimeValue, traceEventsToOpenTelemetrySpans, unknownExecutionAuthority };
package/package.json CHANGED
@@ -1,45 +1,48 @@
1
1
  {
2
2
  "name": "@vite-hub/runtime",
3
- "version": "0.0.1",
3
+ "version": "0.0.3",
4
4
  "description": "Shared runtime context, capability, policy, approval, and tracing primitives for ViteHub.",
5
- "author": "onmax <maximogarciamtnez@gmail.com>",
6
- "license": "Apache-2.0",
5
+ "keywords": [
6
+ "approvals",
7
+ "capabilities",
8
+ "policy",
9
+ "runtime",
10
+ "vitehub"
11
+ ],
7
12
  "homepage": "https://github.com/vite-hub/vitehub#readme",
13
+ "bugs": "https://github.com/vite-hub/vitehub/issues",
14
+ "license": "Apache-2.0",
15
+ "author": "onmax <maximogarciamtnez@gmail.com>",
8
16
  "repository": {
9
17
  "type": "git",
10
18
  "url": "git+https://github.com/vite-hub/vitehub.git",
11
19
  "directory": "packages/runtime"
12
20
  },
13
- "bugs": "https://github.com/vite-hub/vitehub/issues",
14
- "keywords": [
15
- "vitehub",
16
- "runtime",
17
- "capabilities",
18
- "approvals",
19
- "policy"
21
+ "files": [
22
+ "dist",
23
+ "package.json"
20
24
  ],
21
- "sideEffects": false,
22
25
  "type": "module",
26
+ "sideEffects": false,
23
27
  "types": "./dist/index.d.ts",
24
28
  "exports": {
25
29
  ".": "./dist/index.js",
26
30
  "./package.json": "./package.json"
27
31
  },
28
- "files": [
29
- "dist",
30
- "package.json"
31
- ],
32
32
  "devDependencies": {
33
- "@types/node": "^25.6.0",
34
- "publint": "^0.3.15",
35
- "tsdown": "^0.21.8",
36
- "typescript": "^6.0.2",
33
+ "@types/node": "^24.13.3",
34
+ "publint": "^0.3.21",
35
+ "typescript": "^6.0.3",
36
+ "vite-plus": "^0.1.24",
37
37
  "vitest": "^4.1.4"
38
38
  },
39
+ "engines": {
40
+ "node": ">=24.0.0"
41
+ },
39
42
  "scripts": {
40
- "build": "tsdown --tsconfig tsconfig.build.json",
41
- "dev": "tsdown --watch",
43
+ "build": "vp pack",
44
+ "dev": "vp pack --watch",
42
45
  "typecheck": "tsc --noEmit -p ./tsconfig.json",
43
- "test": "pnpm --filter @vite-hub/runtime build && vitest run"
46
+ "test": "vp run -t @vite-hub/runtime#build && vp test"
44
47
  }
45
48
  }