@forg3t/sdk 0.1.3 → 0.1.4

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
@@ -1,63 +1,407 @@
1
- # @forg3t/sdk
2
-
3
- Official TypeScript SDK for the Forg3t Protocol. This SDK allows you to interact with the Forg3t Control Plane to manage projects, submit jobs, verify evidence, and handle webhooks.
4
-
5
- **[Forg3t.io](https://forg3t.io)** is the platform where you can manage your AI Unlearning operations, track compliance, and visualize evidence. This SDK enables you to integrate these capabilities directly into your applications.
6
-
7
- ## Installation
8
-
9
- ```bash
10
- npm install @forg3t/sdk
11
- # or
12
- yarn add @forg3t/sdk
13
- # or
14
- pnpm add @forg3t/sdk
15
- ```
16
-
17
- ## Quick Start
18
-
19
- Initialize the client with your project's API key. You can generate API keys from your [Forg3t Dashboard](https://forg3t.io/dashboard).
20
-
21
- ```typescript
22
- import { Forg3tClient } from '@forg3t/sdk';
23
-
24
- const client = new Forg3tClient({
25
- apiUrl: 'https://api.forg3t.io',
26
- apiKey: 'f3_sk_...',
27
- });
28
-
29
- async function main() {
30
- // Get Project Overview
31
- const project = await client.getProjectOverview('your-project-id');
32
- console.log('Project:', project);
33
-
34
- // Submit an Unlearning Job
35
- const job = await client.submitJob('your-project-id', {
36
- type: 'unlearning',
37
- parameters: {
38
- modelId: 'llama-2-7b',
39
- datasetId: 'copyrighted-books-subset'
40
- }
41
- });
42
- console.log('Unlearning Job Submitted:', job.id);
43
- }
44
-
45
- main().catch(console.error);
46
- ```
47
-
48
- ## Features
49
-
50
- - **AI Unlearning Operations**: Submit and track unlearning jobs programmatically.
51
- - **Verification Evidence**: Retrieve cryptographic proofs and PDF reports for audit trails.
52
- - **Project Management**: View project details and stats.
53
- - **API Key Management**: Create, rotate, and revoke API keys programmatically.
54
- - **Webhooks**: Manage and replay webhook deliveries for real-time integration.
55
-
56
- ## Documentation
57
-
58
- For comprehensive guides and API references, visit [docs.forg3t.io](https://docs.forg3t.io).
59
- To start unlearning your AI models, visit **[Forg3t.io](https://forg3t.io)**.
60
-
61
- ## License
62
-
63
- MIT
1
+ # @forg3t/sdk
2
+
3
+ Official TypeScript SDK for the Forg3t Protocol. This SDK allows you to interact with the Forg3t Control Plane to manage projects, submit jobs, verify evidence, and handle webhooks.
4
+
5
+ **[Forg3t.io](https://forg3t.io)** is the platform where you can manage your AI Unlearning operations, track compliance, and visualize evidence. This SDK enables you to integrate these capabilities directly into your applications.
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ npm install @forg3t/sdk
11
+ # or
12
+ yarn add @forg3t/sdk
13
+ # or
14
+ pnpm add @forg3t/sdk
15
+ ```
16
+
17
+ ## Production Reality
18
+
19
+ This package is live and installable. It is not yet a fully self-serve enterprise onboarding product by itself.
20
+
21
+ Today, the truthful usage pattern is:
22
+
23
+ 1. Forg3t provisions or approves the tenant / project path.
24
+ 2. The customer receives a real project API key.
25
+ 3. The SDK connects to a real control-plane URL.
26
+ 4. Execution then depends on the architecture:
27
+ - API-only / retrieval-based systems use control-plane enforcement and evidence flows.
28
+ - Whitebox model changes require a customer-side whitebox worker path.
29
+
30
+ There is now also a live bearer-token bootstrap path for first-time tenant creation:
31
+
32
+ - `POST /v1/bootstrap/tenant`
33
+ - public hostname: `https://api.forg3t.io`
34
+ - auth mode: dashboard bearer token, not project API key
35
+
36
+ This closes the biggest admin-led onboarding gap, but the published npm package and official customer docs still need to catch up before this can be called fully self-serve.
37
+
38
+ ## Local Development
39
+ 1. **Build**: `npm run build`
40
+ 2. **Typecheck**: `node ../../node_modules/typescript/bin/tsc -p tsconfig.json --noEmit`
41
+ 3. **Examples**: `examples/whitebox-worker.ts` demonstrates customer-infra model editing.
42
+ 4. **Staging smoke**: `npm run smoke:staging` validates request -> job -> terminal status flow.
43
+
44
+ ### Customer Onboarding Smoke
45
+
46
+ Use this as the first real integration gate for a provisioned customer project.
47
+ The production API hostname is:
48
+
49
+ ```bash
50
+ export FORG3T_API_URL=https://api.forg3t.io
51
+ export FORG3T_API_KEY=fg_...
52
+ export FORG3T_PROJECT_ID=... # optional if default project exists
53
+ ```
54
+
55
+ Then run a clean smoke script from your own workspace:
56
+
57
+ ```typescript
58
+ import { Forg3tClient } from '@forg3t/sdk';
59
+
60
+ const client = new Forg3tClient({
61
+ apiUrl: process.env.FORG3T_API_URL,
62
+ apiKey: process.env.FORG3T_API_KEY,
63
+ timeoutMs: 30000,
64
+ });
65
+
66
+ async function main() {
67
+ const me = await client.getCurrentUser();
68
+ const projectId = process.env.FORG3T_PROJECT_ID || me.defaultProjectId;
69
+
70
+ if (!projectId) {
71
+ throw new Error('Set FORG3T_PROJECT_ID or configure a default project first.');
72
+ }
73
+
74
+ const request = await client.createUnlearningRequest(projectId, {
75
+ target: { type: 'phrase', value: 'customer-onboarding-smoke' },
76
+ scope: {},
77
+ accessLevel: 'layer_a_only',
78
+ execution: {
79
+ target: {
80
+ provider: 'custom',
81
+ endpoint: 'https://example.com/inference'
82
+ }
83
+ }
84
+ });
85
+
86
+ console.log({
87
+ requestId: request.id,
88
+ jobId: request.job?.id,
89
+ jobType: request.job?.type,
90
+ jobStatus: request.job?.status
91
+ });
92
+ }
93
+
94
+ main().catch((error) => {
95
+ console.error(error);
96
+ process.exit(1);
97
+ });
98
+ ```
99
+
100
+ This validates:
101
+ - API authentication
102
+ - project resolution
103
+ - unlearning request creation
104
+ - job contract correctness
105
+ - job lifecycle visibility
106
+
107
+ ### First-Time Tenant Bootstrap
108
+
109
+ If you are integrating from a signed-in dashboard or application session, instantiate the SDK with a bearer token and bootstrap the tenant path first:
110
+
111
+ ```typescript
112
+ import { Forg3tClient } from '@forg3t/sdk';
113
+
114
+ const client = new Forg3tClient({
115
+ apiUrl: 'https://api.forg3t.io',
116
+ bearerToken: process.env.FORG3T_BEARER_TOKEN,
117
+ });
118
+
119
+ async function main() {
120
+ const bootstrap = await client.bootstrapTenant({
121
+ tenantName: 'Northstar Bank',
122
+ projectName: 'Retail Banking Assistant',
123
+ integrationType: 'custom',
124
+ integrationName: 'Primary Banking Integration',
125
+ });
126
+
127
+ console.log({
128
+ created: bootstrap.created,
129
+ tenantId: bootstrap.tenant.id,
130
+ projectId: bootstrap.bootstrap.project.id,
131
+ apiKeyPrefix: bootstrap.bootstrap.apiKey.keyPrefix,
132
+ plaintextKeyReturned: Boolean(bootstrap.bootstrap.apiKey.plaintextKey),
133
+ });
134
+ }
135
+
136
+ main().catch((error) => {
137
+ console.error(error);
138
+ process.exit(1);
139
+ });
140
+ ```
141
+
142
+ Notes:
143
+
144
+ - First bootstrap returns the plaintext API key once.
145
+ - Repeating bootstrap with the same bearer token is idempotent and reuses the tenant resources.
146
+ - This flow is live on the control plane today.
147
+
148
+ ### Repo Maintainer Smoke
149
+
150
+ If you are working inside the Forg3t SDK repo itself, you can also run the bundled smoke script:
151
+
152
+ ```bash
153
+ export FORG3T_API_URL=https://api.forg3t.io
154
+ export FORG3T_API_KEY=fg_...
155
+ export FORG3T_PROJECT_ID=...
156
+ npm run smoke:customer-onboarding
157
+ ```
158
+
159
+ ### Known Limitations
160
+ - **Node Runtime**: Whitebox worker and Python runner examples target Node.js + Python environments.
161
+ - **Onchain Verification**: Onchain anchoring is not required for whitebox execution flow and can be integrated later.
162
+
163
+
164
+
165
+ Initialize the client with your project's API key. You can generate API keys from your [Forg3t Dashboard](https://forg3t.io/dashboard).
166
+
167
+ ```typescript
168
+ import { Forg3tClient } from '@forg3t/sdk';
169
+
170
+ const client = new Forg3tClient({
171
+ apiUrl: process.env.FORG3T_API_URL,
172
+ apiKey: process.env.FORG3T_API_KEY,
173
+ });
174
+
175
+ async function main() {
176
+ const me = await client.getCurrentUser();
177
+ const projectId = process.env.FORG3T_PROJECT_ID || me.defaultProjectId;
178
+
179
+ if (!projectId) {
180
+ throw new Error('Set FORG3T_PROJECT_ID or configure a default project first.');
181
+ }
182
+
183
+ const project = await client.getProjectOverview(projectId);
184
+ console.log('Project:', project.name);
185
+ }
186
+
187
+ main().catch(console.error);
188
+ ```
189
+
190
+ ## Features
191
+
192
+ - **AI Unlearning Operations**: Submit and track unlearning jobs programmatically.
193
+ - **Verification Evidence**: Retrieve cryptographic proofs and PDF reports for audit trails.
194
+ - **Project Management**: View project details and stats.
195
+ - **API Key Management**: Create, rotate, and revoke API keys programmatically.
196
+ - **Webhooks**: Manage and replay webhook deliveries for real-time integration.
197
+
198
+ ### Evidence Retrieval
199
+
200
+ ```typescript
201
+ const evidence = await client.getEvidence(jobId);
202
+ // If API returns readiness shape:
203
+ if ('evidenceReady' in evidence && !evidence.evidenceReady) {
204
+ // retry later
205
+ }
206
+
207
+ const evidenceJson = await client.getEvidenceJson(jobId);
208
+ const evidencePdf = await client.getEvidencePdf(jobId, { saveToPath: './evidence.pdf' });
209
+ ```
210
+
211
+ ## Whitebox Worker (Customer Infra)
212
+
213
+ For real model-weight modifications, run a customer-side worker that claims `MODEL_UNLEARN` jobs and executes your training backend adapter in your own infrastructure.
214
+
215
+ ### 1) Submit a `MODEL_UNLEARN` job
216
+
217
+ ```typescript
218
+ import { Forg3tClient, buildModelUnlearningPayload } from '@forg3t/sdk';
219
+
220
+ const client = new Forg3tClient({ apiUrl: process.env.FORG3T_API_URL, apiKey: process.env.FORG3T_API_KEY });
221
+
222
+ const { claim, config } = buildModelUnlearningPayload({
223
+ claim: {
224
+ claim_type: 'DOCUMENT',
225
+ claim_payload: 'customer-record-123',
226
+ scope: 'project',
227
+ assertion: 'must_not_be_recalled'
228
+ },
229
+ model: {
230
+ uri: '/models/llama-7b.safetensors',
231
+ format: 'safetensors'
232
+ },
233
+ target: {
234
+ text: 'customer-record-123'
235
+ },
236
+ plan: {
237
+ method: 'gradient_surgery',
238
+ hyperparameters: { lr: 0.0005, max_steps: 400 }
239
+ }
240
+ });
241
+
242
+ await client.createJob('your-project-id', 'MODEL_UNLEARN', claim, config);
243
+ ```
244
+
245
+ For targeted whitebox localization, provide either:
246
+
247
+ - `config.parameters.target.tokenIds` (preferred), or
248
+ - tokenizer URI in `config.target_config.tokenizer.uri` / `config.parameters.tokenizer.uri`.
249
+
250
+ SDK preflight now enforces this for `MODEL_UNLEARN` submission. To bypass temporarily (not recommended), set:
251
+
252
+ ```bash
253
+ export FORG3T_ALLOW_MODEL_UNLEARN_WITHOUT_LOCALIZATION_INPUT=true
254
+ ```
255
+
256
+ If you use `createUnlearningRequest(...)` with `accessLevel: 'layer_a_and_b'`, include `execution.model.uri` so Control Plane can generate an executable `MODEL_UNLEARN` job:
257
+
258
+ ```typescript
259
+ await client.createUnlearningRequest('your-project-id', {
260
+ target: { type: 'document_id', value: 'customer-record-123' },
261
+ scope: { integrationIds: [] },
262
+ accessLevel: 'layer_a_and_b',
263
+ execution: {
264
+ model: { uri: '/models/llama-7b.safetensors', format: 'safetensors' },
265
+ plan: { method: 'suppression', hyperparameters: { suppression_factor: 0.85, max_edits: 2048 } }
266
+ }
267
+ });
268
+ ```
269
+
270
+ For `accessLevel: 'layer_a_only'`, provide explicit Layer A target config (`execution.target`). This now creates a first-class `BLACKBOX_SUPPRESS` job instead of overloading the retrieval contract:
271
+
272
+ ```typescript
273
+ await client.createUnlearningRequest('your-project-id', {
274
+ target: { type: 'concept', value: 'customer-record-123' },
275
+ scope: { integrationIds: [] },
276
+ accessLevel: 'layer_a_only',
277
+ execution: {
278
+ target: {
279
+ provider: 'openai',
280
+ model: 'gpt-4o-mini'
281
+ }
282
+ }
283
+ });
284
+ ```
285
+
286
+ ### 2) Run worker + adapter in your infra
287
+
288
+ Use the example worker at:
289
+ - `examples/whitebox-worker.ts`
290
+ - `examples/python/weight_surgery_runner.py`
291
+
292
+ Ops installers:
293
+ - `packages/worker/scripts/install-whitebox-gcp.sh` (one-command GCP rollout)
294
+ - `packages/worker/scripts/install-whitebox-airgapped.sh` (one-command offline bundle/install)
295
+
296
+ The worker now supports native adapter modes:
297
+ - `local_command`: run local Python/CLI training jobs inside customer infra.
298
+ - `http`: call your internal training gateway (Kubernetes/SageMaker/Slurm bridge).
299
+
300
+ Install Python deps for the example:
301
+
302
+ ```bash
303
+ pip install -r examples/python/requirements.txt
304
+ ```
305
+
306
+ Example environment for local command mode:
307
+
308
+ ```bash
309
+ export FORG3T_ADAPTER_MODE=local_command
310
+ export FORG3T_PYTHON_BIN=python3
311
+ export FORG3T_DEPLOYMENT_PROFILE=customer_online
312
+ ```
313
+
314
+ Example environment for HTTP mode:
315
+
316
+ ```bash
317
+ export FORG3T_ADAPTER_MODE=http
318
+ export FORG3T_UNLEARNING_URL=https://ml-internal.example.com/unlearn
319
+ export FORG3T_EVALUATION_URL=https://ml-internal.example.com/evaluate
320
+ export FORG3T_ADAPTER_BEARER_TOKEN=...
321
+ export FORG3T_DEPLOYMENT_PROFILE=cloud_managed
322
+ ```
323
+
324
+ Example environment for air-gapped customer deployments:
325
+
326
+ ```bash
327
+ export FORG3T_ADAPTER_MODE=local_command
328
+ export FORG3T_DEPLOYMENT_PROFILE=customer_airgapped
329
+ # optional: allow private DNS hostnames used by local control-plane
330
+ export FORG3T_AIRGAPPED_ALLOWED_HOSTS=cp.internal,forg3t-cp.lan
331
+ ```
332
+
333
+ ### 3) Enforce unlearning quality gates
334
+
335
+ `WhiteboxWorker` supports policy-based quality gates before completing a job:
336
+
337
+ - Presets:
338
+ - `strict`: evaluator required, localization required, `PASS` only.
339
+ - `balanced`: evaluator optional, localization optional, `PASS/REVIEW` allowed.
340
+
341
+ ```typescript
342
+ import { resolveWhiteboxQualityGatePolicy } from '@forg3t/sdk';
343
+
344
+ const strictPolicy = resolveWhiteboxQualityGatePolicy('strict');
345
+ const balancedPolicy = resolveWhiteboxQualityGatePolicy('balanced');
346
+ ```
347
+
348
+ ```typescript
349
+ import { WhiteboxWorker } from '@forg3t/sdk';
350
+
351
+ const worker = new WhiteboxWorker(client, adapter, {
352
+ projectId: process.env.FORG3T_PROJECT_ID!,
353
+ qualityGatePolicy: {
354
+ requireEvaluation: true,
355
+ maxLeakScore: 0.03,
356
+ allowedVerdicts: ['PASS'],
357
+ minChangedTensorCount: 1,
358
+ minChangedParamCount: 1,
359
+ requireModelHashTransition: true,
360
+ requireLocalization: true,
361
+ minLocalizationTokenCoverage: 0.5,
362
+ minLocalizedParamCount: 1,
363
+ minLocalizationConfidence: 0.6
364
+ },
365
+ qualityGateOnFailure: 'fail_job'
366
+ });
367
+ ```
368
+
369
+ Per-job override support:
370
+
371
+ - Include `quality_gate_preset` in `plan.hyperparameters` (`strict` or `balanced`) when creating `MODEL_UNLEARN` requests/jobs.
372
+ - Optional `quality_gate_policy` object can further override preset thresholds.
373
+
374
+ ### 4) Operational hardening (lease-token protected lifecycle)
375
+
376
+ Worker SDK now propagates `claimId` lease tokens on `heartbeat/complete/fail`, and control-plane can enforce strict token checks:
377
+
378
+ ```bash
379
+ export REQUIRE_JOB_CLAIM_TOKEN=1
380
+ ```
381
+
382
+ With this enabled, stale or foreign workers cannot ack jobs they did not claim.
383
+
384
+ ### 5) Privacy defaults (no raw claim payload in result telemetry)
385
+
386
+ `WhiteboxWorker` now defaults to `resultClaimMode: 'hash'` so raw `claim_payload` is not written back to control-plane results:
387
+
388
+ ```typescript
389
+ const worker = new WhiteboxWorker(client, adapter, {
390
+ projectId: process.env.FORG3T_PROJECT_ID!,
391
+ resultClaimMode: 'hash' // default: stores sha256 + payload length
392
+ });
393
+ ```
394
+
395
+ Modes:
396
+ - `hash` (default): sends `claim_payload_sha256` + length.
397
+ - `omit`: omits payload and hash, keeps only claim metadata.
398
+ - `raw`: sends full claim payload (only use if explicitly required).
399
+
400
+ ## Documentation
401
+
402
+ For comprehensive guides and API references, visit [docs.forg3t.io](https://docs.forg3t.io).
403
+ To start unlearning your AI models, visit **[Forg3t.io](https://forg3t.io)**.
404
+
405
+ ## License
406
+
407
+ MIT