@pouchy_ai/world-sdk 0.13.0 → 0.15.0

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/CHANGELOG.md CHANGED
@@ -1,5 +1,50 @@
1
1
  # @pouchy_ai/world-sdk
2
2
 
3
+ ## 0.15.0
4
+
5
+ - `getProgress()` — where a story is and whether it can go on, as a DERIVED
6
+ checkpoint over facts that already committed. Reads nothing into existence:
7
+ no new collection, no model call, no write.
8
+ - The return is a discriminated union. `status: 'unavailable'` carries **no
9
+ `checkpoint`**, so code that forgets to narrow fails loudly instead of reading
10
+ a plausible zero; `resumable` is typed `false` on that arm.
11
+ - `reason` is coarse on purpose. `world_unavailable` covers "no such instance",
12
+ "no access", "package revoked", "package gone" and "contract too new" as one
13
+ word — telling them apart would let a caller map which objects exist by
14
+ reading refusals. `story_reference_invalid` is distinct and leaks nothing: the
15
+ pinned story and its state disagree.
16
+ - The checkpoint pins its provenance — `environmentRevision`, and the story
17
+ package's exact `revision` + `contentHash`. It follows the INSTANCE's pin, so
18
+ publishing a new story revision never changes what a running world reports.
19
+ - **`declaredNodeCount` is not a denominator.** A branching story never visits
20
+ every declared node; there is no percentage field and `completedNodeCount /
21
+ declaredNodeCount` is not a completion ratio. Show two numbers.
22
+ - **`recentProgressRecords` is not a summary.** `{ seq, kind, at }` says a beat
23
+ happened, never what happened in it. Read `/turns` for the lines.
24
+ - `nextOptions` is the same shape and the same derivation the live turn uses —
25
+ never model-generated, capped server-side.
26
+ - Two reads of an unchanged world are byte-identical: no read-time clock, every
27
+ list explicitly ordered, state and ledger taken in one read-only transaction.
28
+
29
+ ## 0.14.0
30
+
31
+ - `deliberate()` and `selectCandidate()` — ask for a few PUBLIC directions a
32
+ beat could take, then commit the one the player chose.
33
+ - Candidates are safe to render straight to a player: `candidateId`, `title`,
34
+ `direction`, `shortTeaser`, `participatingRoles` and nothing else. No
35
+ reasoning, no role secrets, no simulated effects, no scores.
36
+ - `selectCandidate` commits through the ordinary coordinator — same beat, same
37
+ ledger, same `WorldTurnResult`. A deliberation has no privileges over the
38
+ world: its simulated effects are never carried into the real turn.
39
+ - The `envelope` is opaque and belongs on your SERVER. Hand it back unchanged;
40
+ do not send it to a browser. The turn id is fixed inside it, so re-sending the
41
+ same envelope retries rather than committing a second beat.
42
+ - If the world moved since the candidates were produced, `selectCandidate`
43
+ answers 409 `stale_deliberation` having spent nothing — deliberate again.
44
+ - Off unless the world's published revision declares `deliberation`. A world
45
+ without it answers 409 on `deliberate()`, which simply means that story plays
46
+ directly.
47
+
3
48
  ## 0.13.0
4
49
 
5
50
  - `createWorldSession` now returns a typed `WorldSessionResponse` instead of
package/README.md CHANGED
@@ -47,8 +47,12 @@ const world = new PouchyWorldClient({
47
47
 
48
48
  **Running** — `createWorldSession`, `runTurn`, `sendEvent`.
49
49
 
50
- **Reading** — `getWorldState`, `getTurn`, `listTurns`, `listTurnsSince`,
51
- `replayLedger`, `replayLedgerToEnd`.
50
+ **Deliberating** — `deliberate`, `selectCandidate`. Ask for a couple of public
51
+ directions a beat could take, then commit the one the player picked. Off unless
52
+ the world's published revision declares it; the `envelope` is server-side only.
53
+
54
+ **Reading** — `getWorldState`, `getProgress`, `getTurn`, `listTurns`,
55
+ `listTurnsSince`, `replayLedger`, `replayLedgerToEnd`.
52
56
 
53
57
  **Which credential does what.** This matters more than it looks: one of them
54
58
  expires within the hour.
@@ -109,6 +113,27 @@ Both are additive: a turn committed before world API 1.6 carries none of the
109
113
  four turn-time facts (`selectedRoles`, `skippedRoles`, `repairs`,
110
114
  `nextOptions`). Absent means UNKNOWN, never "none".
111
115
 
116
+ **Reopening a story.** `getProgress` answers the question a returning reader's
117
+ client has — where was I, and can I go on? — without replaying anything.
118
+
119
+ ```ts
120
+ const p = await world.getProgress(envId, instanceId);
121
+ if (p.status !== 'ready') return renderStartFresh(); // narrow FIRST
122
+ renderScene(p.checkpoint.currentScene); // may be null
123
+ renderCounts(p.checkpoint.completedNodeCount, p.checkpoint.declaredNodeCount);
124
+ renderDirections(p.checkpoint.nextOptions);
125
+ ```
126
+
127
+ Narrowing on `status` is not politeness: the `unavailable` arm has no
128
+ `checkpoint` key, so skipping the check reads `undefined` rather than telling a
129
+ reader they never started a story they are halfway through.
130
+
131
+ Two shapes it does not have. **`declaredNodeCount` is not a denominator** — a
132
+ branching story never visits every node the author declared, so show the two
133
+ counts, never a percentage. And **`recentProgressRecords` is not a summary**:
134
+ `{ seq, kind, at }` says a beat happened, not what happened in it; the lines
135
+ live behind `getTurn` / `listTurns`.
136
+
112
137
  **Content return** — `createScriptDraft`, `getScriptDraft`, `listScriptDrafts`,
113
138
  `reviewScriptDraft`, `exportScriptDraft`.
114
139
 
package/dist/index.d.ts CHANGED
@@ -4,8 +4,33 @@
4
4
  * a project is running — which is exactly the field you reach for when a
5
5
  * customer's integration behaves like an older SDK than they say they have.
6
6
  * It sat at '0.1.0' for eight releases before anything compared the two. */
7
- export declare const WORLD_SDK_VERSION = "0.13.0";
7
+ export declare const WORLD_SDK_VERSION = "0.15.0";
8
8
  export declare const DEFAULT_BASE_URL = "https://pouchy.ai/v1";
9
+ /** One direction a beat could take. The WHOLE of what a deliberation shows a
10
+ * player: no reasoning, no role secrets, no simulated effects, no scores. */
11
+ export interface WorldDeliberationCandidate {
12
+ candidateId: string;
13
+ title: string;
14
+ /** What the scene will be steered toward. Public, because the player is
15
+ * choosing it and must be able to read what they are choosing. */
16
+ direction: string;
17
+ shortTeaser: string;
18
+ participatingRoles: string[];
19
+ }
20
+ export interface WorldDeliberationResponse {
21
+ candidates: WorldDeliberationCandidate[];
22
+ /** Signed evidence. Opaque — hand it back to `selectCandidate` unchanged. */
23
+ envelope: string;
24
+ expiresAt: number;
25
+ budgetSpent: {
26
+ modelCalls: number;
27
+ tokens: number;
28
+ ms: number;
29
+ };
30
+ /** Why it stopped. A run that hit a ceiling says so rather than letting a
31
+ * short list pass for a complete one. */
32
+ stop: 'complete' | 'candidate_cap' | 'model_call_cap' | 'token_cap' | 'time_cap' | 'no_roles';
33
+ }
9
34
  /** The refusal classes a world call can produce. `unknown` is deliberate: an
10
35
  * unrecognized status is never quietly folded into a neighbour. */
11
36
  export declare const WORLD_ERROR_CODES: readonly ["unauthorized", "forbidden", "not_found", "conflict", "unprocessable", "rate_limited", "payload_too_large", "server_error", "network", "unknown"];
@@ -131,6 +156,68 @@ export interface WorldTurnResult {
131
156
  *
132
157
  * The four turn-time facts are optional because rows committed before world
133
158
  * API 1.6 do not carry them. Absent means UNKNOWN. */
159
+ /** Where a story is, and whether it can go on. World API 1.18.
160
+ *
161
+ * A DISCRIMINATED UNION, not an optional-field bag. The `unavailable` arm has
162
+ * no `checkpoint` key at all, so narrowing on `status` is not a style choice:
163
+ * it is the only way to reach the data, and code that skips it fails loudly
164
+ * instead of reading a plausible zero. `resumable` is typed `false` on that
165
+ * arm, so "unavailable but resumable" cannot be constructed. */
166
+ export type WorldProgressResponse = {
167
+ status: 'ready';
168
+ resumable: boolean;
169
+ checkpoint: WorldProgressCheckpointV1;
170
+ } | {
171
+ status: 'unavailable';
172
+ resumable: false;
173
+ reason: WorldProgressUnavailableReason;
174
+ };
175
+ /** `world_unavailable` is deliberately coarse — no such instance, no access, a
176
+ * revoked or deleted package, a contract too new to read. Distinguishing them
177
+ * would let a caller map which internal objects exist by reading refusals.
178
+ * `story_reference_invalid` is different in kind: the pinned story and the
179
+ * state it is pinned to disagree, which reveals nothing about existence. */
180
+ export type WorldProgressUnavailableReason = 'world_unavailable' | 'story_reference_invalid';
181
+ export interface WorldProgressCheckpointV1 {
182
+ contractVersion: 1;
183
+ /** The revision this INSTANCE is pinned to for life. */
184
+ environmentRevision: number;
185
+ storyPackageRef: {
186
+ packageId: string;
187
+ revision: number;
188
+ contentHash: string;
189
+ };
190
+ stateRevision: number;
191
+ started: boolean;
192
+ /** Null when no scene has been opened. Never a substitute for one the
193
+ * pinned story does not declare — that answers `story_reference_invalid`. */
194
+ currentScene: {
195
+ sceneId: string;
196
+ title: string;
197
+ } | null;
198
+ completedNodeCount: number;
199
+ /** What the AUTHOR declared. NOT a denominator: a branching story never
200
+ * visits every node, so `completedNodeCount / declaredNodeCount` is not a
201
+ * completion ratio. Render them as two numbers. */
202
+ declaredNodeCount: number;
203
+ publicRelations: Array<{
204
+ between: [string, string];
205
+ descriptor: string;
206
+ }>;
207
+ publicRelationsTruncated: boolean;
208
+ /** Newest first. That a beat happened — never what happened in it. */
209
+ recentProgressRecords: Array<{
210
+ seq: number;
211
+ kind: 'turn' | 'event' | 'system';
212
+ at: number;
213
+ }>;
214
+ recentProgressTruncated: boolean;
215
+ nextOptions: Array<{
216
+ branchId: string;
217
+ condition: string;
218
+ }>;
219
+ rebuildable: true;
220
+ }
134
221
  export interface WorldTurnReadback {
135
222
  turnId: string;
136
223
  worldInstanceId: string;
@@ -605,6 +692,26 @@ export declare class PouchyWorldClient {
605
692
  environmentRevision: number;
606
693
  state: Record<string, unknown>;
607
694
  }>;
695
+ /** Where the story is, and whether it can go on. World API 1.18.
696
+ *
697
+ * A DERIVED checkpoint: nothing is stored to answer it, no model is asked,
698
+ * and the story it reports is the package this INSTANCE pinned, at its
699
+ * exact revision and content hash — never whatever was published since.
700
+ *
701
+ * Check `status` before reading anything else. `unavailable` has no
702
+ * `checkpoint` at all, which is deliberate: a caller that skips the check
703
+ * gets `undefined` rather than a plausible zero. Its `reason` is
704
+ * intentionally coarse — one word covers "no such instance", "no access",
705
+ * "package revoked", "package gone" and "contract too new", because telling
706
+ * them apart would let a caller map which objects exist by reading errors.
707
+ *
708
+ * Two things it does NOT give you. There is no completion percentage:
709
+ * `declaredNodeCount` is what the AUTHOR wrote, and a branching story never
710
+ * visits all of it, so a ratio of the two counts is meaningless — show them
711
+ * as two numbers. And `recentProgressRecords` says a beat happened, not
712
+ * what happened in it; for the lines themselves, read the timeline.
713
+ */
714
+ getProgress(environmentId: string, worldInstanceId: string): Promise<WorldProgressResponse>;
608
715
  /** Read back a COMMITTED turn. The recovery path when a response was lost:
609
716
  * it re-runs nothing, and a 404 means the turn never committed. */
610
717
  /** Read a COMMITTED turn back — the recovery path when a response was lost.
@@ -811,6 +918,35 @@ export declare class PouchyWorldClient {
811
918
  * role's private notes. */
812
919
  proposedPatches?: readonly Record<string, unknown>[];
813
920
  }): Promise<WorldTurnResult>;
921
+ /** Ask for a few PUBLIC directions this beat could take, without taking it.
922
+ *
923
+ * Off unless the world's published revision declares `deliberation`. Nothing
924
+ * is written and no candidate is stored: what comes back is a short list
925
+ * plus a signed `envelope` you hand to `selectCandidate`. The candidates are
926
+ * public by construction — no reasoning, no role secrets, no simulated
927
+ * effects — so they are safe to render straight to a player. */
928
+ deliberate(input: {
929
+ environmentId: string;
930
+ worldInstanceId: string;
931
+ requestId?: string;
932
+ text: string;
933
+ model?: string;
934
+ }): Promise<WorldDeliberationResponse>;
935
+ /** Commit the direction the player chose. This IS an ordinary beat — the
936
+ * same coordinator, the same ledger, the same result shape.
937
+ *
938
+ * Re-send the same `envelope` to retry: the turn id is fixed inside it, so a
939
+ * second call is a duplicate rather than a second beat. If the world moved
940
+ * since the candidates were produced, this answers 409 `stale_deliberation`
941
+ * and spends nothing — deliberate again. */
942
+ selectCandidate(input: {
943
+ environmentId: string;
944
+ worldInstanceId: string;
945
+ envelope: string;
946
+ candidateId: string;
947
+ direction: string;
948
+ text: string;
949
+ }): Promise<WorldTurnResult>;
814
950
  /** Send a trusted EVENT into a world. On a `coordinated` world this becomes
815
951
  * one coordinator turn; on an `actor` world it wakes each subscribed role.
816
952
  * Either way `eventId` is the dedupe key — re-send it freely. */
package/dist/index.js CHANGED
@@ -23,9 +23,24 @@ import { createHash, createHmac, randomUUID } from 'node:crypto';
23
23
  * a project is running — which is exactly the field you reach for when a
24
24
  * customer's integration behaves like an older SDK than they say they have.
25
25
  * It sat at '0.1.0' for eight releases before anything compared the two. */
26
- export const WORLD_SDK_VERSION = '0.13.0';
26
+ export const WORLD_SDK_VERSION = '0.15.0';
27
27
  export const DEFAULT_BASE_URL = 'https://pouchy.ai/v1';
28
- // ── errors ─────────────────────────────────────────────────────────────────
28
+ /** Read the commit turn id out of an envelope, so the signature covers the id
29
+ * the server will commit under. The payload half is base64url JSON; the
30
+ * signature is not needed to read it, and reading it proves nothing — the
31
+ * SERVER verifies. This is only so the client signs the right slot. */
32
+ function commitTurnIdOf(envelope) {
33
+ const payload = envelope.slice(0, envelope.lastIndexOf('.'));
34
+ try {
35
+ const json = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'));
36
+ if (typeof json.commitTurnId === 'string' && json.commitTurnId)
37
+ return json.commitTurnId;
38
+ }
39
+ catch {
40
+ /* fall through */
41
+ }
42
+ throw new Error('deliberation envelope is malformed — re-run deliberate()');
43
+ }
29
44
  /** The refusal classes a world call can produce. `unknown` is deliberate: an
30
45
  * unrecognized status is never quietly folded into a neighbour. */
31
46
  export const WORLD_ERROR_CODES = [
@@ -282,6 +297,28 @@ export class PouchyWorldClient {
282
297
  getWorldState(environmentId, worldInstanceId) {
283
298
  return this.read(`/projects/${this.projectId}/environments/${environmentId}/instances/${worldInstanceId}/state`, `/admin/environments/${environmentId}/instances/${worldInstanceId}/state`);
284
299
  }
300
+ /** Where the story is, and whether it can go on. World API 1.18.
301
+ *
302
+ * A DERIVED checkpoint: nothing is stored to answer it, no model is asked,
303
+ * and the story it reports is the package this INSTANCE pinned, at its
304
+ * exact revision and content hash — never whatever was published since.
305
+ *
306
+ * Check `status` before reading anything else. `unavailable` has no
307
+ * `checkpoint` at all, which is deliberate: a caller that skips the check
308
+ * gets `undefined` rather than a plausible zero. Its `reason` is
309
+ * intentionally coarse — one word covers "no such instance", "no access",
310
+ * "package revoked", "package gone" and "contract too new", because telling
311
+ * them apart would let a caller map which objects exist by reading errors.
312
+ *
313
+ * Two things it does NOT give you. There is no completion percentage:
314
+ * `declaredNodeCount` is what the AUTHOR wrote, and a branching story never
315
+ * visits all of it, so a ratio of the two counts is meaningless — show them
316
+ * as two numbers. And `recentProgressRecords` says a beat happened, not
317
+ * what happened in it; for the lines themselves, read the timeline.
318
+ */
319
+ getProgress(environmentId, worldInstanceId) {
320
+ return this.read(`/projects/${this.projectId}/environments/${environmentId}/instances/${worldInstanceId}/progress`, `/admin/environments/${environmentId}/instances/${worldInstanceId}/progress`);
321
+ }
285
322
  /** Read back a COMMITTED turn. The recovery path when a response was lost:
286
323
  * it re-runs nothing, and a 404 means the turn never committed. */
287
324
  /** Read a COMMITTED turn back — the recovery path when a response was lost.
@@ -521,6 +558,39 @@ export class PouchyWorldClient {
521
558
  };
522
559
  return this.signed(`/projects/${this.projectId}/environments/${input.environmentId}/instances/${input.worldInstanceId}/turns`, body, turnId);
523
560
  }
561
+ /** Ask for a few PUBLIC directions this beat could take, without taking it.
562
+ *
563
+ * Off unless the world's published revision declares `deliberation`. Nothing
564
+ * is written and no candidate is stored: what comes back is a short list
565
+ * plus a signed `envelope` you hand to `selectCandidate`. The candidates are
566
+ * public by construction — no reasoning, no role secrets, no simulated
567
+ * effects — so they are safe to render straight to a player. */
568
+ deliberate(input) {
569
+ const requestId = input.requestId ?? newTurnId('dlb-req');
570
+ const body = { requestId, text: input.text, ...(input.model ? { model: input.model } : {}) };
571
+ return this.signed(`/projects/${this.projectId}/environments/${input.environmentId}/instances/${input.worldInstanceId}/deliberations`, body,
572
+ // The signature's id slot is namespaced, so a deliberation signature
573
+ // can never be replayed onto the turn door.
574
+ `dlb:${requestId}`);
575
+ }
576
+ /** Commit the direction the player chose. This IS an ordinary beat — the
577
+ * same coordinator, the same ledger, the same result shape.
578
+ *
579
+ * Re-send the same `envelope` to retry: the turn id is fixed inside it, so a
580
+ * second call is a duplicate rather than a second beat. If the world moved
581
+ * since the candidates were produced, this answers 409 `stale_deliberation`
582
+ * and spends nothing — deliberate again. */
583
+ selectCandidate(input) {
584
+ const body = {
585
+ envelope: input.envelope,
586
+ candidateId: input.candidateId,
587
+ direction: input.direction,
588
+ text: input.text
589
+ };
590
+ // The id slot is the turn id the envelope already fixed, so the signature
591
+ // covers the id the server will actually commit under.
592
+ return this.signed(`/projects/${this.projectId}/environments/${input.environmentId}/instances/${input.worldInstanceId}/deliberations/select`, body, commitTurnIdOf(input.envelope));
593
+ }
524
594
  /** Send a trusted EVENT into a world. On a `coordinated` world this becomes
525
595
  * one coordinator turn; on an `actor` world it wakes each subscribed role.
526
596
  * Either way `eventId` is the dedupe key — re-send it freely. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pouchy_ai/world-sdk",
3
- "version": "0.13.0",
3
+ "version": "0.15.0",
4
4
  "description": "Server-side TypeScript client for Pouchy World \u2014 story packages, world definitions, world sessions, coordinated turns, trusted events, replay verification and script drafts. Node only: it holds a project Secret Key and a source signing key, which never belong in a browser or a mobile app.",
5
5
  "type": "module",
6
6
  "license": "SEE LICENSE IN LICENSE",