@dvmkit/sdk 0.1.3-rc.7 → 0.1.4-rc.7

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
@@ -2,21 +2,105 @@
2
2
 
3
3
  Build Digital Vending Machines: accountless HTTPS services with typed inputs, jobs, and payment rails.
4
4
 
5
- ## Development
5
+ Requires Node.js 22 or later. This is pre-1.0 alpha software: pin the exact package version and read the [release notes](./CHANGELOG.md) before upgrading.
6
+
7
+ ## Quickstart: a free DVM
8
+
9
+ Create a project and install the SDK:
10
+
11
+ ```sh
12
+ mkdir hello-dvm && cd hello-dvm
13
+ npm init -y
14
+ npm install --save-exact @dvmkit/sdk
15
+ ```
16
+
17
+ Save this as `handler.mjs`:
18
+
19
+ ```js
20
+ import { configureDVM, z } from "@dvmkit/sdk";
21
+
22
+ export default configureDVM({
23
+ name: "hello",
24
+ capability: "echo",
25
+ input: z.object({ text: z.string().min(1) }),
26
+ example: { text: "hello" },
27
+ onJob(ctx) {
28
+ ctx.artifact({ mime_type: "text/plain", data: ctx.input.text });
29
+ ctx.complete("Echoed the input");
30
+ },
31
+ });
32
+ ```
33
+
34
+ Save this as `server.mjs`, then run it with `node server.mjs`:
35
+
36
+ ```js
37
+ import { serve } from "@dvmkit/sdk/server";
38
+ import dvm from "./handler.mjs";
39
+
40
+ await serve(dvm, { devMode: true });
41
+ ```
42
+
43
+ Submit a local request. `devMode` makes Postgres optional and skips payment verification when no Cashu mint is configured:
44
+
45
+ ```sh
46
+ curl -sS http://localhost:8080/v1/job \
47
+ -H 'content-type: application/json' \
48
+ --data '{"capability":"echo","data":{"text":"hello"}}'
49
+ ```
50
+
51
+ Test the handler without opening a port or configuring a payment rail:
52
+
53
+ ```js
54
+ import assert from "node:assert/strict";
55
+ import test from "node:test";
56
+ import { createTestContext } from "@dvmkit/sdk/testing";
57
+ import dvm from "./handler.mjs";
58
+
59
+ test("echoes its input", async () => {
60
+ const ctx = createTestContext({ input: { text: "hello" } });
61
+ await dvm.capabilities.echo.onJob(ctx);
62
+ assert.equal(ctx.completed, true);
63
+ assert.equal(ctx.messages[0].content.data, "hello");
64
+ });
65
+ ```
66
+
67
+ Run that file with `node --test handler.test.mjs`. The repository carries the complete version under [`examples/quickstart`](./examples/quickstart), plus runnable [signed-auth/custom-route](./examples/authenticated-route) and [payment/lifecycle](./examples/payments-and-lifecycle) examples.
68
+
69
+ ## Public entry points
70
+
71
+ | Import | Use it for |
72
+ | --- | --- |
73
+ | `@dvmkit/sdk` | DVM descriptors, handler context, bundled Zod, pricing, signing and safe-fetch helpers |
74
+ | `@dvmkit/sdk/server` | Node hosting, Postgres stores, signed-request auth, compatibility gates and payment infrastructure |
75
+ | `@dvmkit/sdk/testing` | Deterministic handler contexts and in-memory stores |
76
+
77
+ The generated [API reference](./docs/API.md) lists every declaration under these three entries. Deep imports from `dist/` are unsupported.
78
+
79
+ ## Production next steps
80
+
81
+ - Use Postgres through `DATABASE_URL`; production boot refuses an in-memory job store unless you deliberately supply another durable implementation.
82
+ - Add `auth: secp256k1Auth()` for caller-owned state. The host automatically uses a Postgres replay store when one is available; a per-process replay window is unsafe across replicas.
83
+ - Configure only the rails you operate: Cashu, x402, and Tempo are job payment methods. Lightning is a receive-only prepaid-credit funding leg. Keep every private key, wallet connection, and platform token in your secret store rather than source.
84
+ - A `credit` block opts into reusable prepaid balances and their reclaim obligations. Reusable channels return undrawn collateral through their channel lifecycle; one-payment stablecoin funding is disabled unless `allowOneShotStablecoin: true` because it creates manual refunds. Run and monitor the documented reclaim/payout worker.
85
+ - Honour `ctx.signal`, use `ctx.fetch` for abortable provider calls, and declare provider cost with `ctx.cost` only after the durable step that incurred it.
86
+
87
+ The public [SDK guide](https://dvmkit.com/docs/sdk) covers signed requests, custom routes, rail configuration, credit reclaim, persistence, and deployment in depth. The [protocol guide](https://dvmkit.com/docs/protocol) specifies the HTTP contract.
88
+
89
+ ## Repository development
6
90
 
7
91
  Use the Node.js release in `.nvmrc` (Node 22). Install with `npm ci`, then run the same gate CI runs with `npm run verify`: the toolchain check, lint, build, typecheck (including the release scripts under `checkJs`), unit and database tests, the public API surface and package-shape checks, a consumer install, a public-safety scan, the release contract, and a clean-install smoke.
8
92
 
9
93
  `DATABASE_URL` is optional locally. Without it the database suite is skipped rather than passed, and `verify` says so in its summary, because a skipped suite verified nothing and must not be reported as green. Point `DATABASE_URL` at a scratch Postgres to run it, and pass `npm run verify -- --require-database` to make a missing one a failure, which is what CI does.
10
94
 
11
- The public surface is exactly `@dvmkit/sdk`, `@dvmkit/sdk/server`, and `@dvmkit/sdk/testing`. There is a fourth entry point, `@dvmkit/sdk/internal`, which is not part of it; see below. Documentation is at [dvmkit.ai](https://dvmkit.ai/docs/sdk).
95
+ The public surface is exactly `@dvmkit/sdk`, `@dvmkit/sdk/server`, and `@dvmkit/sdk/testing`.
12
96
 
13
97
  ## Compatibility and versioning
14
98
 
15
99
  This is pre-1.0 alpha software and the promises match that. Breaking changes can land in any release, they are announced in the release notes for the release that carries them, and there is no long-term support release. Security fixes are made on the latest published release rather than backported.
16
100
 
17
- The public surface is exactly three entry points: `@dvmkit/sdk`, `@dvmkit/sdk/server`, and `@dvmkit/sdk/testing`. Nothing reachable only through a deep path into `dist/` is public, nothing under `@dvmkit/sdk/internal` is public, and `npm run check:api` pins every exported declaration name against `api-surface.json`, so a change to that surface is a deliberate, reviewed act rather than a side effect.
101
+ Nothing reachable only through a deep path into `dist/` is public. `npm run check:api` pins every exported declaration name against `api-surface.json` and the generated API reference, so a change to the supported surface is a deliberate, reviewed act rather than a side effect.
18
102
 
19
- Wire compatibility with callers is separate from the package version and is declared per endpoint. A server built on this SDK answers `DVM-Protocol-Version: 1`, and an individual endpoint may require a set of named capability tokens the caller advertises, a minimum caller version, or both. Capability tokens are additive, so an endpoint that declares no requirement stays reachable by a caller that sends no compatibility headers at all. A caller that cannot meet what an endpoint declares gets HTTP 426 naming the required capabilities and, where one is declared, the minimum version. The protocol is specified at [dvmkit.ai/docs/protocol](https://dvmkit.ai/docs/protocol).
103
+ Wire compatibility with callers is separate from the package version and is declared per endpoint. A server built on this SDK answers `DVM-Protocol-Version: 1`, and an individual endpoint may require a set of named capability tokens the caller advertises, a minimum caller version, or both. Capability tokens are additive, so an endpoint that declares no requirement stays reachable by a caller that sends no compatibility headers at all. A caller that cannot meet what an endpoint declares gets HTTP 426 naming the required capabilities and, where one is declared, the minimum version. The protocol is specified at [dvmkit.com/docs/protocol](https://dvmkit.com/docs/protocol).
20
104
 
21
105
  ## Job credentials
22
106
 
@@ -34,13 +118,28 @@ The same values are accepted as `--endpoint <url>` and `--job-token <hex>`. Thes
34
118
 
35
119
  If an upgrade broke something for you, an [API compatibility report](https://github.com/dvmkit/sdk/issues/new/choose) is the most useful thing you can send us. It tells us which parts of the published surface people actually build on, which no test of ours can.
36
120
 
37
- ## Internal entry point
121
+ ## Per-job costs
122
+
123
+ A handler can declare what a job cost **you**, the builder, to serve — a vendor API call, a GPU minute, a per-request licence fee — and the SDK reports it to the platform alongside what the caller paid, so your dashboard can state a margin instead of guessing at one.
124
+
125
+ ```ts
126
+ const transcript = await ctx.step("transcribe", async () => {
127
+ const result = await whisper(audio);
128
+ ctx.cost({ amount: result.seconds * 0.0001, currency: "usd" });
129
+ return result;
130
+ });
131
+ ctx.artifact({ mime_type: "text/plain", data: transcript.text });
132
+ ```
133
+
134
+ `amount` is in whole currency units, like every other money figure you hand the SDK. Call it once per cost you incur; the declarations for one job are summed, and only the total is rounded, to a millionth of a unit. That ordering is what makes fine-grained declarations safe: a per-token charge of $0.0000003 is below the reported resolution on its own, but a thousand of them still add up to $0.0003 rather than to nothing. Every call in a job must name the same currency.
38
135
 
39
- `@dvmkit/sdk/internal` exists for one consumer: the dvmkit platform, which runs on this source instead of keeping a fork of it. Do not build on it.
136
+ Three things worth knowing:
40
137
 
41
- It carries no stability promise of any kind. A name under it can change meaning, change signature, or disappear in any release, including a patch release, and that is not a breaking change: it needs no `!` marker, no `BREAKING CHANGE:` footer, and no note in the release notes. It is not documented, its contents track what the platform happens to need, and it is excluded from everything the three public entry points promise above.
138
+ - **Declaring nothing is not declaring zero.** A job whose handler never calls `ctx.cost` reports no cost at all, and the dashboard says the margin is unknown rather than showing it as 100%. `ctx.cost({ amount: 0, currency: "usd" })` is how you say a job genuinely cost you nothing.
139
+ - **Declare the cost where you incur it, including inside `ctx.step`.** The step cache carries those declarations with the result and applies them once when a replay skips the body.
140
+ - **Every terminal job reports its declared cost.** A paid completion carries the cost on its revenue report. A free completion, failure, or cancellation sends a separate cost-only report and does not create revenue.
42
141
 
43
- The names in it are still pinned in `api-surface.json`, so a change to them is visible in review rather than silent; the pin records what moved, it does not promise that it will not move. If something under `./internal` is genuinely useful to a third party, the way to get it is to ask for it: graduating a name to `.`, `./server` or `./testing` is a deliberate, reviewed `feat`, and only then does it acquire the compatibility promises on this page.
142
+ The cost is yours, never the caller's: it is recorded separately from what the caller paid and is never netted against it. Both report shapes use the same durable outbox. Cost-only reports are keyed on the job id and revisioned, so retries and cross-machine updates converge on the latest cumulative value. With the Postgres job store, boot-time and periodic reconciliation enqueue any terminal cost revision that a process exited before reporting.
44
143
 
45
144
  ## Contributing
46
145
 
@@ -11,24 +11,31 @@ var StepCache = class _StepCache {
11
11
  }
12
12
  /** Get a cached step result. Throws if not present. */
13
13
  get(id) {
14
- if (!this.cache.has(id)) {
15
- throw new Error(`StepCache: no cached result for step "${id}"`);
16
- }
17
- return this.cache.get(id);
14
+ return this.getRecord(id).value;
15
+ }
16
+ /** Get a cached step record, including replay metadata. Throws if not present. */
17
+ getRecord(id) {
18
+ const record = this.cache.get(id);
19
+ if (record === void 0) throw new Error(`StepCache: no cached result for step "${id}"`);
20
+ return record;
18
21
  }
19
22
  /** Cache a step result. */
20
- set(id, value) {
21
- this.cache.set(id, value);
23
+ set(id, value, costs) {
24
+ this.cache.set(id, {
25
+ id,
26
+ value,
27
+ ...costs !== void 0 && costs.length > 0 ? { costs: costs.map(({ amount, currency }) => ({ amount, currency })) } : {}
28
+ });
22
29
  }
23
30
  /** Export all cached steps for persistence. */
24
31
  serialize() {
25
- return [...this.cache.entries()].map(([id, value]) => ({ id, value }));
32
+ return [...this.cache.values()];
26
33
  }
27
34
  /** Restore a StepCache from persisted records. */
28
35
  static deserialize(records) {
29
36
  const cache = new _StepCache();
30
- for (const { id, value } of records) {
31
- cache.set(id, value);
37
+ for (const { id, value, costs } of records) {
38
+ cache.set(id, value, costs);
32
39
  }
33
40
  return cache;
34
41
  }
@@ -5,13 +5,13 @@ import {
5
5
  // src/lib/mints.ts
6
6
  var RECOMMENDED_MINTS = [
7
7
  {
8
- name: "Testnut",
9
- description: "Cashu test mint \u2014 use for testing only, not real funds",
10
- url: "https://testnut.cashu.space"
8
+ name: "Coinos",
9
+ description: "Primary Cashu mint accepted by dvmkit DVMs",
10
+ url: "https://mint.coinos.io"
11
11
  },
12
12
  {
13
13
  name: "Voltz Mint",
14
- description: "Production Cashu mint by the Voltz Wallet team",
14
+ description: "Fallback Cashu mint accepted by dvmkit DVMs",
15
15
  url: "https://mint.lnvoltz.com"
16
16
  }
17
17
  ];
@@ -6,6 +6,7 @@ import {
6
6
  import { randomUUID } from "crypto";
7
7
  var ENDPOINTS = {
8
8
  revenue: "/_internal/job-revenue",
9
+ cost: "/_internal/job-cost",
9
10
  deposit: "/_internal/credit-deposit",
10
11
  release: "/_internal/credit-draw-release",
11
12
  drain: "/_internal/credit-drain",
@@ -129,6 +130,10 @@ var RevenueReporter = class _RevenueReporter {
129
130
  async report(payload) {
130
131
  return this.enqueue("revenue", payload, payload.jobId);
131
132
  }
133
+ /** Persist a zero-revenue job cost and attempt immediate delivery. */
134
+ async reportCost(payload) {
135
+ return this.enqueue("cost", payload, payload.jobId);
136
+ }
132
137
  /**
133
138
  * Join a credit deposit to the caller-owned rail transaction.
134
139
  *