lodestar-ai-sdk 0.1.0 → 0.2.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.
package/README.md CHANGED
@@ -17,14 +17,14 @@ const lodestar = new Lodestar({ apiKey: process.env.LODESTAR_API_KEY! });
17
17
 
18
18
  // 1. Standalone System-One probe (~20ms, $0.03/1M input, $0 output)
19
19
  const check = await lodestar.probes.eval({
20
- model: "qwen3-32b",
20
+ model: "lodestar-s1",
21
21
  input: "Who designed the Kessington Bridge in Cleveland?",
22
22
  probes: ["hallucination_risk", "prompt_injection"],
23
23
  });
24
24
 
25
25
  // 2. Glass-Box Chat Completion with Token-0 abort_if + declarative onAbort remediation
26
26
  const res = await lodestar.chat.create({
27
- model: "qwen3-32b",
27
+ model: "lodestar-s1",
28
28
  messages: [{ role: "user", content: "Return JSON with keys service, status." }],
29
29
  probes: ["hallucination_risk", "prompt_injection"],
30
30
  abortIf: { hallucination_risk: 0.75, prompt_injection: 0.7 },
@@ -41,4 +41,27 @@ const res = await lodestar.chat.create({
41
41
  },
42
42
  patches: ["strict-json"],
43
43
  });
44
+
45
+ // 3. Continual Learning (`teach()` / `revert()`) on `lodestar-s1` or OpenAI/Anthropic/Gemini
46
+ const agentName = "acme-agent";
47
+ const reply = await lodestar.chat.completions.create({
48
+ model: agentName,
49
+ messages: [{ role: "user", content: "Please refund my $120 order immediately." }],
50
+ });
51
+ const lesson = await lodestar.models.teach({
52
+ model: agentName,
53
+ traceId: reply.id,
54
+ correction: "Never promise refunds over $50 without manager approval.",
55
+ });
56
+ await lodestar.models.revert({ model: agentName, lessonId: lesson.id });
57
+
58
+ // 4. Open-Weight Model & LoRA Supply-Chain Security Audit (SARIF 2.1.0 + SVG badge)
59
+ const job = await lodestar.audit.lora({
60
+ lora: "my-org/qwen3-8b-vendor-lora",
61
+ mode: "weights-only",
62
+ profile: "strict-regulated",
63
+ });
64
+ const done = await lodestar.audit.wait(job.id);
65
+ const sarif = await lodestar.audit.sarif(done.id);
66
+ const badgeSvg = await lodestar.audit.badgeSvg(done.id);
44
67
  ```
package/dist/index.d.ts CHANGED
@@ -1,8 +1,11 @@
1
1
  export declare const DEFAULT_BASE_URL = "https://api.lodestar.so/v1";
2
+ export declare const DEFAULT_MODEL = "lodestar-s1";
2
3
  export interface LodestarOptions {
3
4
  apiKey: string;
4
5
  baseUrl?: string;
5
6
  fetch?: typeof globalThis.fetch;
7
+ /** Enable Zero-Data-Retention mode (`X-Lodestar-ZDR: true`) on all requests. */
8
+ zdr?: boolean;
6
9
  }
7
10
  export interface ChatMessage {
8
11
  role: "system" | "user" | "assistant" | string;
@@ -14,6 +17,7 @@ export interface ProbeEvalParams {
14
17
  input?: string;
15
18
  messages?: ChatMessage[];
16
19
  system?: string;
20
+ zdr?: boolean;
17
21
  }
18
22
  export interface ProbeEvalResponse {
19
23
  id: string;
@@ -43,6 +47,7 @@ export interface ProbeCreateParams {
43
47
  }>;
44
48
  positiveLabel?: string;
45
49
  negativeLabel?: string;
50
+ zdr?: boolean;
46
51
  }
47
52
  export interface ProbeCreateResponse {
48
53
  id: string;
@@ -61,7 +66,7 @@ export interface OnAbortRule {
61
66
  action: OnAbortAction;
62
67
  /** Required when `action` is `"retry_with_patch"`. */
63
68
  patches?: string[];
64
- /** Required when `action` is `"fallback_model"` (e.g. `"qwen3-32b"` or BYOK `"gpt-4o"` / `"claude-sonnet-4-20250514"`). */
69
+ /** Required when `action` is `"fallback_model"` (e.g. `"lodestar-s1-precise"` or BYOK `"gpt-6.2-astra"` / `"claude-sonnet-5-5"` / `"gemini-4-carbon"`). */
65
70
  model?: string;
66
71
  /** Optional provider override for BYOK fallback: `"lodestar" | "openai" | "anthropic" | "gemini" | "custom"`. */
67
72
  provider?: "lodestar" | "openai" | "anthropic" | "gemini" | "custom";
@@ -96,20 +101,178 @@ export interface ChatCreateParams {
96
101
  abortIf?: Record<string, number | string>;
97
102
  onAbort?: OnAbortConfig;
98
103
  patches?: string[];
104
+ memoryModel?: string;
105
+ customerId?: string;
106
+ zdr?: boolean;
99
107
  max_tokens?: number;
100
108
  temperature?: number;
101
109
  [extra: string]: unknown;
102
110
  }
111
+ export interface AppliedLessonTelemetry {
112
+ id: string;
113
+ version: number;
114
+ kind: "guard" | "policy" | "skill" | string;
115
+ delivery_mode: "guard" | "episodic" | "hybrid" | "weight" | string;
116
+ scope?: "shared" | "customer" | string;
117
+ customer_id?: string | null;
118
+ score: number;
119
+ threshold: number;
120
+ view: "full_context" | "last_turn" | string;
121
+ }
103
122
  export interface LodestarMetadata {
123
+ trace_id?: string;
104
124
  probes: Record<string, number>;
105
125
  aborted: boolean;
106
126
  abort_reason: string | null;
107
127
  patches_applied: string[];
108
128
  probe_ms: number;
129
+ zdr?: boolean;
109
130
  early_exit_layer?: number | null;
110
131
  vllm_model?: string;
132
+ model_version?: number;
133
+ lessons_evaluated?: number;
134
+ lessons_applied?: AppliedLessonTelemetry[];
135
+ customer_id?: string | null;
111
136
  remediation?: LodestarRemediationMetadata;
112
137
  }
138
+ export interface ContinualModelUpstream {
139
+ provider: "openai" | "anthropic" | "gemini" | "custom";
140
+ model: string;
141
+ upstream_url?: string;
142
+ }
143
+ export interface ContinualModelCreateParams {
144
+ name: string;
145
+ baseModel?: string;
146
+ upstream?: ContinualModelUpstream;
147
+ consolidationPolicy?: Record<string, unknown>;
148
+ }
149
+ export interface ContinualTeachParams {
150
+ model: string;
151
+ correction?: string;
152
+ customerId?: string;
153
+ traceId?: string;
154
+ traceIds?: string[];
155
+ messages?: ChatMessage[];
156
+ badOutput?: string;
157
+ goodOutput?: string;
158
+ when?: string;
159
+ examples?: Array<string | Record<string, unknown>>;
160
+ positive?: Array<string | {
161
+ text: string;
162
+ }>;
163
+ negative?: Array<string | {
164
+ text: string;
165
+ }>;
166
+ kind?: "auto" | "guard" | "policy" | "skill";
167
+ delivery?: "auto" | "guard" | "episodic" | "hybrid" | "weight";
168
+ rollout?: "active" | "canary" | "staging";
169
+ canaryPct?: number;
170
+ guardAction?: Record<string, unknown>;
171
+ tags?: string[];
172
+ metadata?: Record<string, unknown>;
173
+ idempotencyKey?: string;
174
+ upstream?: ContinualModelUpstream;
175
+ zdr?: boolean;
176
+ }
177
+ export interface ContinualLessonResponse {
178
+ id: string;
179
+ object: "lodestar.lesson";
180
+ model: string;
181
+ version: number;
182
+ status: string;
183
+ kind: string;
184
+ delivery_mode: string;
185
+ scope?: "shared" | "customer" | string;
186
+ customer_id?: string | null;
187
+ canary_pct: number;
188
+ consolidation_status: string;
189
+ superseded_by: string | null;
190
+ superseded_lesson_ids: string[];
191
+ correction: string;
192
+ scoped_rule: string;
193
+ trigger_summary: string;
194
+ tags: string[];
195
+ metadata: Record<string, unknown>;
196
+ probe: {
197
+ layer: number;
198
+ threshold: number;
199
+ };
200
+ trace_count: number;
201
+ trigger_count: number;
202
+ certification: Record<string, unknown> | null;
203
+ created_at: string;
204
+ updated_at: string;
205
+ }
206
+ export interface ContinualRouteParams {
207
+ model: string;
208
+ messages?: ChatMessage[];
209
+ prompt?: string;
210
+ customerId?: string;
211
+ sessionId?: string;
212
+ zdr?: boolean;
213
+ }
214
+ export interface ContinualRouteRule {
215
+ id: string;
216
+ version: number;
217
+ kind: string;
218
+ delivery_mode: string;
219
+ scope: "shared" | "customer" | string;
220
+ customer_id: string | null;
221
+ rule: string;
222
+ score: number;
223
+ threshold: number;
224
+ view: string;
225
+ verified: boolean;
226
+ guard_action?: Record<string, unknown>;
227
+ }
228
+ export interface ContinualRouteResponse {
229
+ object: "lodestar.route";
230
+ id: string;
231
+ model: string;
232
+ model_version: number;
233
+ customer_id: string | null;
234
+ blocked: boolean;
235
+ guard: {
236
+ lesson_id: string;
237
+ version: number;
238
+ scope: string;
239
+ customer_id: string | null;
240
+ rule: string;
241
+ message: string;
242
+ score: number;
243
+ threshold: number;
244
+ } | null;
245
+ lessons_evaluated: number;
246
+ rules: ContinualRouteRule[];
247
+ system_patch: string;
248
+ route_ms: number;
249
+ verifier_used: boolean;
250
+ top_scores: Array<{
251
+ id: string;
252
+ score: number;
253
+ threshold: number;
254
+ view: string;
255
+ }>;
256
+ }
257
+ export interface ContinualCustomerSummary {
258
+ customer_id: string;
259
+ active_lessons: number;
260
+ total_lessons: number;
261
+ }
262
+ export interface ContinualRevertParams {
263
+ model: string;
264
+ lessonId?: string;
265
+ toVersion?: number;
266
+ }
267
+ export interface ContinualRevertResponse {
268
+ object: "lodestar.revert";
269
+ model: string;
270
+ version: number;
271
+ reverted_lesson_ids: string[];
272
+ restored_lesson_ids: string[];
273
+ active_lessons: number;
274
+ refit_ms: number;
275
+ }
113
276
  export interface ChatCompletionResponse {
114
277
  id: string;
115
278
  object: "chat.completion";
@@ -127,6 +290,68 @@ export interface ChatCompletionResponse {
127
290
  };
128
291
  lodestar: LodestarMetadata;
129
292
  }
293
+ export type AuditMode = "weights-only" | "standard" | "deep";
294
+ export type AuditProfile = "enterprise-default" | "strict-regulated" | "fine-tune-qa";
295
+ export interface CheckpointAuditParams {
296
+ base: string;
297
+ candidate: string;
298
+ mode?: AuditMode;
299
+ profile?: AuditProfile;
300
+ policy?: Record<string, unknown>;
301
+ policyYaml?: string;
302
+ strict?: boolean;
303
+ jlens?: "skip" | "cached" | "auto";
304
+ noHash?: boolean;
305
+ skipDirections?: boolean;
306
+ webhook?: string;
307
+ webhookHeaders?: Record<string, string>;
308
+ sync?: boolean;
309
+ }
310
+ export interface LoRAAuditParams {
311
+ lora: string;
312
+ base?: string;
313
+ mode?: AuditMode;
314
+ profile?: AuditProfile;
315
+ policy?: Record<string, unknown>;
316
+ policyYaml?: string;
317
+ strict?: boolean;
318
+ jlens?: "skip" | "cached" | "auto";
319
+ noHash?: boolean;
320
+ skipDirections?: boolean;
321
+ webhook?: string;
322
+ webhookHeaders?: Record<string, string>;
323
+ sync?: boolean;
324
+ }
325
+ export interface AuditJobResponse {
326
+ id: string;
327
+ object: "lodestar.audit_job";
328
+ kind: "checkpoint" | "lora";
329
+ status: "queued" | "running" | "completed" | "failed";
330
+ base: string | null;
331
+ candidate: string;
332
+ mode: AuditMode;
333
+ profile: string;
334
+ strict: boolean;
335
+ verdict: "PASS" | "WARN" | "FAIL" | null;
336
+ risk_score: number | null;
337
+ exit_code: number | null;
338
+ findings_count: number;
339
+ created_at: number;
340
+ started_at: number | null;
341
+ completed_at: number | null;
342
+ elapsed_sec: number | null;
343
+ progress: string[];
344
+ error: string | null;
345
+ webhook_dispatched: boolean;
346
+ links: {
347
+ self: string;
348
+ sarif: string;
349
+ markdown: string;
350
+ html: string;
351
+ badge: string;
352
+ };
353
+ result?: Record<string, unknown> | null;
354
+ }
130
355
  export declare class LodestarAPIError extends Error {
131
356
  statusCode: number;
132
357
  body: string;
@@ -134,10 +359,12 @@ export declare class LodestarAPIError extends Error {
134
359
  }
135
360
  export declare class Lodestar {
136
361
  readonly baseUrl: string;
362
+ readonly zdr: boolean;
137
363
  private readonly apiKey;
138
364
  private readonly _fetch;
139
365
  constructor(opts: LodestarOptions);
140
366
  private headers;
367
+ private requestText;
141
368
  private request;
142
369
  readonly probes: {
143
370
  list: (model?: string) => Promise<unknown[]>;
@@ -145,10 +372,59 @@ export declare class Lodestar {
145
372
  create: (params: ProbeCreateParams) => Promise<ProbeCreateResponse>;
146
373
  export: (probeId: string) => Promise<Record<string, unknown>>;
147
374
  };
375
+ private _chatCreate;
376
+ private _chatStream;
148
377
  readonly chat: {
149
378
  create: (params: ChatCreateParams) => Promise<ChatCompletionResponse>;
150
379
  stream: (params: ChatCreateParams) => AsyncGenerator<Record<string, unknown>, void, void>;
380
+ completions: {
381
+ create: (params: ChatCreateParams) => Promise<ChatCompletionResponse>;
382
+ stream: (params: ChatCreateParams) => AsyncGenerator<Record<string, unknown>, void, void>;
383
+ };
384
+ };
385
+ readonly audit: {
386
+ checkpoint: (params: CheckpointAuditParams) => Promise<AuditJobResponse>;
387
+ lora: (params: LoRAAuditParams) => Promise<AuditJobResponse>;
388
+ get: (jobId: string) => Promise<AuditJobResponse>;
389
+ wait: (jobId: string, opts?: {
390
+ pollIntervalMs?: number;
391
+ timeoutMs?: number;
392
+ }) => Promise<AuditJobResponse>;
393
+ list: (opts?: {
394
+ status?: string;
395
+ verdict?: string;
396
+ limit?: number;
397
+ }) => Promise<AuditJobResponse[]>;
398
+ policies: () => Promise<unknown[]>;
399
+ sarif: (jobId: string) => Promise<Record<string, unknown>>;
400
+ markdown: (jobId: string) => Promise<string>;
401
+ html: (jobId: string) => Promise<string>;
402
+ badgeSvg: (jobId: string) => Promise<string>;
403
+ };
404
+ readonly models: (() => Promise<unknown[]>) & {
405
+ list: () => Promise<unknown[]>;
406
+ get: (model: string) => Promise<Record<string, unknown>>;
407
+ create: (params: ContinualModelCreateParams) => Promise<Record<string, unknown>>;
408
+ teach: (params: ContinualTeachParams) => Promise<ContinualLessonResponse>;
409
+ route: (params: ContinualRouteParams) => Promise<ContinualRouteResponse>;
410
+ customers: (model: string, opts?: {
411
+ limit?: number;
412
+ }) => Promise<ContinualCustomerSummary[]>;
413
+ revert: (params: ContinualRevertParams) => Promise<ContinualRevertResponse>;
414
+ lessons: (model: string, opts?: {
415
+ status?: string;
416
+ customerId?: string;
417
+ includeShared?: boolean;
418
+ limit?: number;
419
+ }) => Promise<ContinualLessonResponse[]>;
420
+ getLesson: (model: string, lessonId: string) => Promise<ContinualLessonResponse>;
421
+ updateLesson: (model: string, lessonId: string, updates: Record<string, unknown>) => Promise<ContinualLessonResponse>;
422
+ consolidate: (model: string, lessonId: string, options?: {
423
+ sync?: boolean;
424
+ rank?: number;
425
+ steps?: number;
426
+ lr?: number;
427
+ }) => Promise<Record<string, unknown>>;
151
428
  };
152
- models: () => Promise<unknown[]>;
153
429
  usage: (limit?: number) => Promise<Record<string, unknown>>;
154
430
  }
package/dist/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  export const DEFAULT_BASE_URL = "https://api.lodestar.so/v1";
2
+ export const DEFAULT_MODEL = "lodestar-s1";
2
3
  export class LodestarAPIError extends Error {
3
4
  statusCode;
4
5
  body;
@@ -11,6 +12,7 @@ export class LodestarAPIError extends Error {
11
12
  }
12
13
  export class Lodestar {
13
14
  baseUrl;
15
+ zdr;
14
16
  apiKey;
15
17
  _fetch;
16
18
  constructor(opts) {
@@ -20,14 +22,18 @@ export class Lodestar {
20
22
  this.apiKey = key;
21
23
  this.baseUrl = (opts.baseUrl || DEFAULT_BASE_URL).replace(/\/+$/, "");
22
24
  this._fetch = opts.fetch || globalThis.fetch;
25
+ this.zdr = Boolean(opts.zdr);
23
26
  }
24
27
  headers() {
25
- return {
28
+ const hdrs = {
26
29
  Authorization: `Bearer ${this.apiKey}`,
27
30
  "Content-Type": "application/json",
28
31
  };
32
+ if (this.zdr)
33
+ hdrs["X-Lodestar-ZDR"] = "true";
34
+ return hdrs;
29
35
  }
30
- async request(method, path, body) {
36
+ async requestText(method, path, body) {
31
37
  const res = await this._fetch(`${this.baseUrl}${path}`, {
32
38
  method,
33
39
  headers: this.headers(),
@@ -46,7 +52,10 @@ export class Lodestar {
46
52
  }
47
53
  throw new LodestarAPIError(res.status, msg, text);
48
54
  }
49
- return JSON.parse(text);
55
+ return text;
56
+ }
57
+ async request(method, path, body) {
58
+ return JSON.parse(await this.requestText(method, path, body));
50
59
  }
51
60
  probes = {
52
61
  list: async (model) => {
@@ -55,88 +64,235 @@ export class Lodestar {
55
64
  return out.data;
56
65
  },
57
66
  eval: (params) => this.request("POST", "/probes/eval", {
58
- model: params.model ?? "qwen3-32b",
67
+ model: params.model ?? DEFAULT_MODEL,
59
68
  probes: params.probes,
60
69
  input: params.input,
61
70
  messages: params.messages,
62
71
  system: params.system,
72
+ ...(params.zdr !== undefined ? { zdr: params.zdr } : {}),
63
73
  }),
64
74
  create: (params) => this.request("POST", "/probes/create", {
65
- model: params.model ?? "qwen3-32b",
75
+ model: params.model ?? DEFAULT_MODEL,
66
76
  name: params.name,
67
77
  positive: params.positive,
68
78
  negative: params.negative,
69
79
  positive_label: params.positiveLabel ?? "Positive",
70
80
  negative_label: params.negativeLabel ?? "Negative",
81
+ ...(params.zdr !== undefined ? { zdr: params.zdr } : {}),
71
82
  }),
72
83
  export: (probeId) => this.request("GET", `/probes/${encodeURIComponent(probeId)}/export`),
73
84
  };
74
- chat = {
75
- create: (params) => {
76
- const { probes, abortIf, onAbort, patches, model, ...rest } = params;
77
- const lodestar = {};
78
- if (probes?.length)
79
- lodestar.probes = probes;
80
- if (abortIf && Object.keys(abortIf).length)
81
- lodestar.abort_if = abortIf;
82
- if (onAbort && Object.keys(onAbort).length)
83
- lodestar.on_abort = onAbort;
84
- if (patches?.length)
85
- lodestar.patches = patches;
86
- return this.request("POST", "/chat/completions", {
85
+ _chatCreate = (params) => {
86
+ const { probes, abortIf, onAbort, patches, memoryModel, customerId, zdr, model, ...rest } = params;
87
+ const lodestar = {};
88
+ if (probes?.length)
89
+ lodestar.probes = probes;
90
+ if (abortIf && Object.keys(abortIf).length)
91
+ lodestar.abort_if = abortIf;
92
+ if (onAbort && Object.keys(onAbort).length)
93
+ lodestar.on_abort = onAbort;
94
+ if (patches?.length)
95
+ lodestar.patches = patches;
96
+ if (memoryModel)
97
+ lodestar.memory_model = memoryModel;
98
+ if (customerId)
99
+ lodestar.customer_id = customerId;
100
+ if (zdr !== undefined)
101
+ lodestar.zdr = zdr;
102
+ return this.request("POST", "/chat/completions", {
103
+ ...rest,
104
+ model: model ?? DEFAULT_MODEL,
105
+ stream: false,
106
+ ...(Object.keys(lodestar).length ? { lodestar } : {}),
107
+ });
108
+ };
109
+ _chatStream = async function* (params) {
110
+ const { probes, abortIf, onAbort, patches, memoryModel, customerId, zdr, model, ...rest } = params;
111
+ const lodestar = {};
112
+ if (probes?.length)
113
+ lodestar.probes = probes;
114
+ if (abortIf && Object.keys(abortIf).length)
115
+ lodestar.abort_if = abortIf;
116
+ if (onAbort && Object.keys(onAbort).length)
117
+ lodestar.on_abort = onAbort;
118
+ if (patches?.length)
119
+ lodestar.patches = patches;
120
+ if (memoryModel)
121
+ lodestar.memory_model = memoryModel;
122
+ if (customerId)
123
+ lodestar.customer_id = customerId;
124
+ if (zdr !== undefined)
125
+ lodestar.zdr = zdr;
126
+ const res = await this._fetch(`${this.baseUrl}/chat/completions`, {
127
+ method: "POST",
128
+ headers: this.headers(),
129
+ body: JSON.stringify({
87
130
  ...rest,
88
- model: model ?? "qwen3-32b",
89
- stream: false,
131
+ model: model ?? DEFAULT_MODEL,
132
+ stream: true,
90
133
  ...(Object.keys(lodestar).length ? { lodestar } : {}),
91
- });
92
- },
93
- stream: async function* (params) {
94
- const { probes, abortIf, onAbort, patches, model, ...rest } = params;
95
- const lodestar = {};
96
- if (probes?.length)
97
- lodestar.probes = probes;
98
- if (abortIf && Object.keys(abortIf).length)
99
- lodestar.abort_if = abortIf;
100
- if (onAbort && Object.keys(onAbort).length)
101
- lodestar.on_abort = onAbort;
102
- if (patches?.length)
103
- lodestar.patches = patches;
104
- const res = await this._fetch(`${this.baseUrl}/chat/completions`, {
105
- method: "POST",
106
- headers: this.headers(),
107
- body: JSON.stringify({
108
- ...rest,
109
- model: model ?? "qwen3-32b",
110
- stream: true,
111
- ...(Object.keys(lodestar).length ? { lodestar } : {}),
112
- }),
113
- });
114
- if (!res.ok || !res.body) {
115
- const txt = await res.text();
116
- throw new LodestarAPIError(res.status, txt.slice(0, 300), txt);
134
+ }),
135
+ });
136
+ if (!res.ok || !res.body) {
137
+ const txt = await res.text();
138
+ throw new LodestarAPIError(res.status, txt.slice(0, 300), txt);
139
+ }
140
+ const reader = res.body.getReader();
141
+ const decoder = new TextDecoder();
142
+ let buf = "";
143
+ while (true) {
144
+ const { done, value } = await reader.read();
145
+ if (done)
146
+ break;
147
+ buf += decoder.decode(value, { stream: true });
148
+ const lines = buf.split("\n");
149
+ buf = lines.pop() || "";
150
+ for (const raw of lines) {
151
+ const line = raw.trim();
152
+ if (!line.startsWith("data:"))
153
+ continue;
154
+ const payload = line.slice(5).trim();
155
+ if (!payload || payload === "[DONE]")
156
+ continue;
157
+ yield JSON.parse(payload);
117
158
  }
118
- const reader = res.body.getReader();
119
- const decoder = new TextDecoder();
120
- let buf = "";
159
+ }
160
+ }.bind(this);
161
+ chat = {
162
+ create: (params) => this._chatCreate(params),
163
+ stream: (params) => this._chatStream(params),
164
+ completions: {
165
+ create: (params) => this._chatCreate(params),
166
+ stream: (params) => this._chatStream(params),
167
+ },
168
+ };
169
+ audit = {
170
+ checkpoint: (params) => this.request("POST", "/audit/checkpoint", {
171
+ base: params.base,
172
+ candidate: params.candidate,
173
+ mode: params.mode ?? "weights-only",
174
+ profile: params.profile ?? "enterprise-default",
175
+ policy: params.policy,
176
+ policy_yaml: params.policyYaml,
177
+ strict: params.strict ?? false,
178
+ jlens: params.jlens ?? "skip",
179
+ no_hash: params.noHash ?? false,
180
+ skip_directions: params.skipDirections ?? false,
181
+ webhook: params.webhook,
182
+ webhook_headers: params.webhookHeaders,
183
+ sync: params.sync ?? false,
184
+ }),
185
+ lora: (params) => this.request("POST", "/audit/lora", {
186
+ lora: params.lora,
187
+ base: params.base,
188
+ mode: params.mode ?? "weights-only",
189
+ profile: params.profile ?? "enterprise-default",
190
+ policy: params.policy,
191
+ policy_yaml: params.policyYaml,
192
+ strict: params.strict ?? false,
193
+ jlens: params.jlens ?? "skip",
194
+ no_hash: params.noHash ?? false,
195
+ skip_directions: params.skipDirections ?? false,
196
+ webhook: params.webhook,
197
+ webhook_headers: params.webhookHeaders,
198
+ sync: params.sync ?? false,
199
+ }),
200
+ get: (jobId) => this.request("GET", `/audit/jobs/${encodeURIComponent(jobId)}`),
201
+ wait: async (jobId, opts) => {
202
+ const interval = Math.max(50, opts?.pollIntervalMs ?? 500);
203
+ const deadline = Date.now() + (opts?.timeoutMs ?? 600_000);
121
204
  while (true) {
122
- const { done, value } = await reader.read();
123
- if (done)
124
- break;
125
- buf += decoder.decode(value, { stream: true });
126
- const lines = buf.split("\n");
127
- buf = lines.pop() || "";
128
- for (const raw of lines) {
129
- const line = raw.trim();
130
- if (!line.startsWith("data:"))
131
- continue;
132
- const payload = line.slice(5).trim();
133
- if (!payload || payload === "[DONE]")
134
- continue;
135
- yield JSON.parse(payload);
136
- }
205
+ const job = await this.audit.get(jobId);
206
+ if (job.status !== "queued" && job.status !== "running")
207
+ return job;
208
+ if (Date.now() >= deadline)
209
+ throw new Error(`Audit job ${jobId} timed out`);
210
+ await new Promise((r) => setTimeout(r, interval));
137
211
  }
138
- }.bind(this),
212
+ },
213
+ list: async (opts) => {
214
+ const qs = new URLSearchParams();
215
+ if (opts?.status)
216
+ qs.set("status", opts.status);
217
+ if (opts?.verdict)
218
+ qs.set("verdict", opts.verdict);
219
+ if (opts?.limit)
220
+ qs.set("limit", String(opts.limit));
221
+ const q = qs.toString();
222
+ const out = await this.request("GET", `/audit/jobs${q ? `?${q}` : ""}`);
223
+ return out.data;
224
+ },
225
+ policies: async () => (await this.request("GET", "/audit/policies")).data,
226
+ sarif: (jobId) => this.request("GET", `/audit/jobs/${encodeURIComponent(jobId)}/sarif`),
227
+ markdown: (jobId) => this.requestText("GET", `/audit/jobs/${encodeURIComponent(jobId)}/markdown`),
228
+ html: (jobId) => this.requestText("GET", `/audit/jobs/${encodeURIComponent(jobId)}/report.html`),
229
+ badgeSvg: (jobId) => this.requestText("GET", `/audit/jobs/${encodeURIComponent(jobId)}/badge.svg`),
139
230
  };
140
- models = async () => (await this.request("GET", "/models")).data;
231
+ models = Object.assign(async () => (await this.request("GET", "/models")).data, {
232
+ list: async () => (await this.request("GET", "/models")).data,
233
+ get: (model) => this.request("GET", `/models/${encodeURIComponent(model)}`),
234
+ create: (params) => this.request("POST", "/models", {
235
+ name: params.name,
236
+ base_model: params.baseModel ?? DEFAULT_MODEL,
237
+ ...(params.upstream ? { upstream: params.upstream } : {}),
238
+ ...(params.consolidationPolicy ? { consolidation_policy: params.consolidationPolicy } : {}),
239
+ }),
240
+ teach: (params) => this.request("POST", `/models/${encodeURIComponent(params.model)}/teach`, {
241
+ ...(params.correction !== undefined ? { correction: params.correction } : {}),
242
+ ...(params.customerId !== undefined ? { customer_id: params.customerId } : {}),
243
+ ...(params.traceId !== undefined ? { trace_id: params.traceId } : {}),
244
+ ...(params.traceIds !== undefined ? { trace_ids: params.traceIds } : {}),
245
+ ...(params.messages !== undefined ? { messages: params.messages } : {}),
246
+ ...(params.badOutput !== undefined ? { bad_output: params.badOutput } : {}),
247
+ ...(params.goodOutput !== undefined ? { good_output: params.goodOutput } : {}),
248
+ ...(params.when !== undefined ? { when: params.when } : {}),
249
+ ...(params.examples !== undefined ? { examples: params.examples } : {}),
250
+ ...(params.positive !== undefined ? { positive: params.positive } : {}),
251
+ ...(params.negative !== undefined ? { negative: params.negative } : {}),
252
+ kind: params.kind ?? "auto",
253
+ delivery: params.delivery ?? "auto",
254
+ rollout: params.rollout ?? "active",
255
+ ...(params.canaryPct !== undefined ? { canary_pct: params.canaryPct } : {}),
256
+ ...(params.guardAction !== undefined ? { guard_action: params.guardAction } : {}),
257
+ ...(params.tags !== undefined ? { tags: params.tags } : {}),
258
+ ...(params.metadata !== undefined ? { metadata: params.metadata } : {}),
259
+ ...(params.idempotencyKey !== undefined ? { idempotency_key: params.idempotencyKey } : {}),
260
+ ...(params.upstream !== undefined ? { upstream: params.upstream } : {}),
261
+ ...(params.zdr !== undefined ? { zdr: params.zdr } : {}),
262
+ }),
263
+ route: (params) => this.request("POST", `/models/${encodeURIComponent(params.model)}/route`, {
264
+ ...(params.messages !== undefined ? { messages: params.messages } : {}),
265
+ ...(params.prompt !== undefined ? { prompt: params.prompt } : {}),
266
+ ...(params.customerId !== undefined ? { customer_id: params.customerId } : {}),
267
+ ...(params.sessionId !== undefined ? { session_id: params.sessionId } : {}),
268
+ ...(params.zdr !== undefined ? { zdr: params.zdr } : {}),
269
+ }),
270
+ customers: async (model, opts) => {
271
+ const q = opts?.limit ? `?limit=${encodeURIComponent(String(opts.limit))}` : "";
272
+ const out = await this.request("GET", `/models/${encodeURIComponent(model)}/customers${q}`);
273
+ return out.data;
274
+ },
275
+ revert: (params) => this.request("POST", `/models/${encodeURIComponent(params.model)}/revert`, {
276
+ ...(params.lessonId !== undefined ? { lesson_id: params.lessonId } : {}),
277
+ ...(params.toVersion !== undefined ? { to_version: params.toVersion } : {}),
278
+ }),
279
+ lessons: async (model, opts) => {
280
+ const qs = new URLSearchParams();
281
+ if (opts?.status)
282
+ qs.set("status", opts.status);
283
+ if (opts?.customerId !== undefined)
284
+ qs.set("customer_id", opts.customerId);
285
+ if (opts?.includeShared)
286
+ qs.set("include_shared", "true");
287
+ if (opts?.limit)
288
+ qs.set("limit", String(opts.limit));
289
+ const q = qs.toString();
290
+ const out = await this.request("GET", `/models/${encodeURIComponent(model)}/lessons${q ? `?${q}` : ""}`);
291
+ return out.data;
292
+ },
293
+ getLesson: (model, lessonId) => this.request("GET", `/models/${encodeURIComponent(model)}/lessons/${encodeURIComponent(lessonId)}`),
294
+ updateLesson: (model, lessonId, updates) => this.request("PATCH", `/models/${encodeURIComponent(model)}/lessons/${encodeURIComponent(lessonId)}`, updates),
295
+ consolidate: (model, lessonId, options = {}) => this.request("POST", `/models/${encodeURIComponent(model)}/lessons/${encodeURIComponent(lessonId)}/consolidate`, options),
296
+ });
141
297
  usage = (limit = 25) => this.request("GET", `/usage?limit=${limit}`);
142
298
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lodestar-ai-sdk",
3
- "version": "0.1.0",
3
+ "version": "0.2.1",
4
4
  "description": "Zero-dependency TypeScript/JavaScript SDK for Lodestar Glass-Box Inference & Open System-One Probes (api.lodestar.so/v1)",
5
5
  "homepage": "https://lodestar.so/docs",
6
6
  "repository": {