@serene-pub/sdk 0.6.0-pr-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.
Files changed (187) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +17 -0
  3. package/README.md +368 -0
  4. package/dist/actions.d.ts +572 -0
  5. package/dist/actions.js +829 -0
  6. package/dist/annexFields.d.ts +234 -0
  7. package/dist/annexFields.js +413 -0
  8. package/dist/announce.d.ts +464 -0
  9. package/dist/announce.js +426 -0
  10. package/dist/attributes.d.ts +670 -0
  11. package/dist/attributes.js +904 -0
  12. package/dist/bands.d.ts +125 -0
  13. package/dist/bands.js +256 -0
  14. package/dist/builder.d.ts +683 -0
  15. package/dist/builder.js +677 -0
  16. package/dist/candidates.d.ts +109 -0
  17. package/dist/candidates.js +118 -0
  18. package/dist/capabilities.d.ts +744 -0
  19. package/dist/capabilities.js +679 -0
  20. package/dist/channels.d.ts +106 -0
  21. package/dist/channels.js +129 -0
  22. package/dist/clauses.d.ts +40 -0
  23. package/dist/clauses.js +43 -0
  24. package/dist/component.d.ts +33 -0
  25. package/dist/component.js +27 -0
  26. package/dist/componentBuild.d.ts +48 -0
  27. package/dist/componentBuild.js +84 -0
  28. package/dist/componentClient.d.ts +100 -0
  29. package/dist/componentClient.js +13 -0
  30. package/dist/componentImports.d.ts +51 -0
  31. package/dist/componentImports.js +106 -0
  32. package/dist/componentModule.d.ts +8 -0
  33. package/dist/componentModule.js +270 -0
  34. package/dist/componentWire.d.ts +130 -0
  35. package/dist/componentWire.js +280 -0
  36. package/dist/config.d.ts +295 -0
  37. package/dist/config.js +231 -0
  38. package/dist/connections.d.ts +89 -0
  39. package/dist/connections.js +131 -0
  40. package/dist/declarations.d.ts +290 -0
  41. package/dist/declarations.js +794 -0
  42. package/dist/descriptors.d.ts +1774 -0
  43. package/dist/descriptors.js +1329 -0
  44. package/dist/dev.d.ts +136 -0
  45. package/dist/dev.js +161 -0
  46. package/dist/document.d.ts +202 -0
  47. package/dist/document.js +312 -0
  48. package/dist/engines.d.ts +117 -0
  49. package/dist/engines.js +203 -0
  50. package/dist/eventMapLaws.d.ts +63 -0
  51. package/dist/eventMapLaws.js +128 -0
  52. package/dist/events.d.ts +554 -0
  53. package/dist/events.js +633 -0
  54. package/dist/executor.d.ts +771 -0
  55. package/dist/executor.js +1829 -0
  56. package/dist/extension.d.ts +448 -0
  57. package/dist/extension.js +315 -0
  58. package/dist/facets.d.ts +53 -0
  59. package/dist/facets.js +60 -0
  60. package/dist/foldedSections.d.ts +74 -0
  61. package/dist/foldedSections.js +161 -0
  62. package/dist/genres.d.ts +507 -0
  63. package/dist/genres.js +633 -0
  64. package/dist/guardedConnection.d.ts +138 -0
  65. package/dist/guardedConnection.js +341 -0
  66. package/dist/handlebarsReach.d.ts +122 -0
  67. package/dist/handlebarsReach.js +222 -0
  68. package/dist/hash.d.ts +146 -0
  69. package/dist/hash.js +166 -0
  70. package/dist/hookGrants.d.ts +47 -0
  71. package/dist/hookGrants.js +68 -0
  72. package/dist/hooks.d.ts +290 -0
  73. package/dist/hooks.js +113 -0
  74. package/dist/hostElements.d.ts +447 -0
  75. package/dist/hostElements.js +702 -0
  76. package/dist/i18n.d.ts +94 -0
  77. package/dist/i18n.js +123 -0
  78. package/dist/identity.d.ts +93 -0
  79. package/dist/identity.js +135 -0
  80. package/dist/index.d.ts +85 -0
  81. package/dist/index.js +176 -0
  82. package/dist/layout.d.ts +194 -0
  83. package/dist/layout.js +40 -0
  84. package/dist/media.d.ts +202 -0
  85. package/dist/media.js +70 -0
  86. package/dist/messageBlocks.d.ts +487 -0
  87. package/dist/messageBlocks.js +683 -0
  88. package/dist/migration.d.ts +128 -0
  89. package/dist/migration.js +261 -0
  90. package/dist/names.d.ts +78 -0
  91. package/dist/names.js +136 -0
  92. package/dist/nodeInput.d.ts +399 -0
  93. package/dist/nodeInput.js +178 -0
  94. package/dist/participants.d.ts +291 -0
  95. package/dist/participants.js +252 -0
  96. package/dist/personGate.d.ts +62 -0
  97. package/dist/personGate.js +77 -0
  98. package/dist/pick.d.ts +84 -0
  99. package/dist/pick.js +103 -0
  100. package/dist/pluginHarness.d.ts +235 -0
  101. package/dist/pluginHarness.js +558 -0
  102. package/dist/pluginPermissions.d.ts +25 -0
  103. package/dist/pluginPermissions.js +97 -0
  104. package/dist/pluginRuleRef.d.ts +13 -0
  105. package/dist/pluginRuleRef.js +10 -0
  106. package/dist/predicates.d.ts +182 -0
  107. package/dist/predicates.js +249 -0
  108. package/dist/preview.d.ts +120 -0
  109. package/dist/preview.js +82 -0
  110. package/dist/promptBlocks.d.ts +130 -0
  111. package/dist/promptBlocks.js +197 -0
  112. package/dist/rankingDecisions.d.ts +60 -0
  113. package/dist/rankingDecisions.js +48 -0
  114. package/dist/receipt.d.ts +313 -0
  115. package/dist/receipt.js +60 -0
  116. package/dist/receiverRules.d.ts +24 -0
  117. package/dist/receiverRules.js +94 -0
  118. package/dist/refs.d.ts +117 -0
  119. package/dist/refs.js +137 -0
  120. package/dist/registry.d.ts +230 -0
  121. package/dist/registry.js +273 -0
  122. package/dist/review.d.ts +108 -0
  123. package/dist/review.js +97 -0
  124. package/dist/sampling.d.ts +152 -0
  125. package/dist/sampling.js +712 -0
  126. package/dist/scope.d.ts +65 -0
  127. package/dist/scope.js +128 -0
  128. package/dist/scripts.d.ts +243 -0
  129. package/dist/scripts.js +326 -0
  130. package/dist/sessionLayout.d.ts +339 -0
  131. package/dist/sessionLayout.js +503 -0
  132. package/dist/sessionSettings.d.ts +70 -0
  133. package/dist/sessionSettings.js +2 -0
  134. package/dist/settings.d.ts +501 -0
  135. package/dist/settings.js +604 -0
  136. package/dist/settingsSlot.d.ts +108 -0
  137. package/dist/settingsSlot.js +166 -0
  138. package/dist/shapes.d.ts +373 -0
  139. package/dist/shapes.js +408 -0
  140. package/dist/sheets.d.ts +165 -0
  141. package/dist/sheets.js +251 -0
  142. package/dist/statShapes.d.ts +96 -0
  143. package/dist/statShapes.js +112 -0
  144. package/dist/status.d.ts +103 -0
  145. package/dist/status.js +125 -0
  146. package/dist/storage.d.ts +145 -0
  147. package/dist/storage.js +33 -0
  148. package/dist/storyTime.d.ts +308 -0
  149. package/dist/storyTime.js +560 -0
  150. package/dist/surfaces.d.ts +501 -0
  151. package/dist/surfaces.js +292 -0
  152. package/dist/template.d.ts +312 -0
  153. package/dist/template.js +554 -0
  154. package/dist/templateCheck.d.ts +60 -0
  155. package/dist/templateCheck.js +516 -0
  156. package/dist/templateFit.d.ts +157 -0
  157. package/dist/templateFit.js +349 -0
  158. package/dist/templateIds.d.ts +138 -0
  159. package/dist/templateIds.js +144 -0
  160. package/dist/templateScopeAt.d.ts +131 -0
  161. package/dist/templateScopeAt.js +354 -0
  162. package/dist/testing.d.ts +177 -0
  163. package/dist/testing.js +383 -0
  164. package/dist/tokenizers.d.ts +113 -0
  165. package/dist/tokenizers.js +184 -0
  166. package/dist/turnLock.d.ts +96 -0
  167. package/dist/turnLock.js +79 -0
  168. package/dist/turnOrder.d.ts +143 -0
  169. package/dist/turnOrder.js +128 -0
  170. package/dist/validate.d.ts +74 -0
  171. package/dist/validate.js +1399 -0
  172. package/dist/values.d.ts +212 -0
  173. package/dist/values.js +390 -0
  174. package/dist/variables.d.ts +493 -0
  175. package/dist/variables.js +662 -0
  176. package/dist/verdicts.d.ts +275 -0
  177. package/dist/verdicts.js +348 -0
  178. package/dist/widgetDecls.d.ts +88 -0
  179. package/dist/widgetDecls.js +119 -0
  180. package/dist/widgets.d.ts +1527 -0
  181. package/dist/widgets.js +208 -0
  182. package/dist/wire.d.ts +126 -0
  183. package/dist/wire.js +140 -0
  184. package/dist/worldinfo.d.ts +150 -0
  185. package/dist/worldinfo.js +212 -0
  186. package/host-elements.d.ts +914 -0
  187. package/package.json +67 -0
@@ -0,0 +1,208 @@
1
+ /**
2
+ * The widget data contract — ONE envelope every session widget receives,
3
+ * native and frame alike (PLAN 25, ruled 2026-08-30).
4
+ *
5
+ * A native widget reads these sections through the host's in-document context
6
+ * (live, reactive); a frame receives the same sections snapshotted over its
7
+ * port. Field-for-field identical: reactivity is the native analog of a push,
8
+ * and that is the whole of the difference. The declarations live here so the
9
+ * two deliveries cannot drift — a plugin compiled against this package sees
10
+ * exactly the shapes an instance sends.
11
+ *
12
+ * These types are TRANSPORT-NEUTRAL. The frame wire that carries them is
13
+ * `surfaces.ts` (`HostFrameMessage` / `FrameHostMessage`); the host internals
14
+ * that produce them — measuring a box, deciding a grant — are core's and are
15
+ * not declared here.
16
+ *
17
+ * ## Two version clocks
18
+ *
19
+ * - `WIDGET_PROTOCOL` versions the TRANSPORT — the verbs (`action` / `invoke`
20
+ * / `request` / `menu` / `on`) and the message kinds. Rev only when the wire
21
+ * itself changes.
22
+ * - Each DATA section is a bag of versioned shapes (`layout: { v1 }`, …). When
23
+ * a pre-existing key inside a section changes meaning, emit `v2` alongside
24
+ * `v1` for a transition window; old widgets read `.v1`, new ones read `.v2`.
25
+ * ADDITIVE keys go straight into the existing `v1` — no bump.
26
+ *
27
+ * ## Base vs scoped
28
+ *
29
+ * Base sections ({@link WIDGET_BASE_SECTIONS}: layout / session / channels /
30
+ * messages / props / actions / settings / annex / locale / viewer /
31
+ * turnOrder) are delivered to every widget that READS them (R75,
32
+ * `WidgetDecl.reads`; a declaration without `reads` reads all of them, which
33
+ * is every widget written before R75). Scoped sections
34
+ * ({@link WidgetScopedSections}, the one table) appear ONLY when the widget
35
+ * declared the scope AND it was granted — the same deny-by-default a frame
36
+ * gets, applied at projection so a native widget is no more privileged.
37
+ * Absence means "not granted", never a silent empty — or "not posted yet":
38
+ * which of the two, the host says with `grants` (the scopes the widget
39
+ * holds, on mount and on every change), so a widget draws "not granted"
40
+ * rather than loading forever.
41
+ */
42
+ /**
43
+ * @experimental The message-row columns a host never posts to a widget — the
44
+ * bookkeeping {@link MessageV1} withholds. The one list: a host's projection
45
+ * ({@link projectMessageRow}) and `MessageV1`'s doc comment both follow it.
46
+ */
47
+ export const MESSAGE_HOST_FIELDS = Object.freeze([
48
+ 'userId',
49
+ 'queueItemId',
50
+ 'debugMeta',
51
+ 'embedding',
52
+ 'embeddingModel',
53
+ 'embeddingSourceHash',
54
+ 'embedTextHash',
55
+ 'vectorizedAt',
56
+ 'version',
57
+ ]);
58
+ const HOST_FIELD_SET = new Set(MESSAGE_HOST_FIELDS);
59
+ /**
60
+ * @experimental A message row as it may cross to a widget: a shallow copy
61
+ * without {@link MESSAGE_HOST_FIELDS}. Every road a row takes to a widget —
62
+ * the `messages` post, a `channel` post, a `messages` page — goes through
63
+ * this. A non-object is returned as it is.
64
+ */
65
+ export function projectMessageRow(row) {
66
+ if (!row || typeof row !== 'object' || Array.isArray(row))
67
+ return row;
68
+ const out = {};
69
+ for (const key of Object.keys(row))
70
+ if (!HOST_FIELD_SET.has(key))
71
+ out[key] = row[key];
72
+ return out;
73
+ }
74
+ /**
75
+ * {@link WidgetScopedSections} at runtime: scope → the name its section is
76
+ * posted under. Typed off the table, so a scope missing here, or a name that
77
+ * disagrees with it, does not compile.
78
+ * @experimental
79
+ */
80
+ export const WIDGET_SCOPED_SECTIONS = Object.freeze({
81
+ 'session:full': 'session_full',
82
+ 'session:state': 'session_state',
83
+ persona: 'persona',
84
+ characters: 'characters',
85
+ lore: 'lore',
86
+ });
87
+ const SCOPED_SECTION_NAMES = new Set(Object.values(WIDGET_SCOPED_SECTIONS));
88
+ /** Is this a scoped section's posted name — what a receiver checks an incoming `scoped` message against. @experimental */
89
+ export const isWidgetScopedSectionName = (name) => typeof name === 'string' && SCOPED_SECTION_NAMES.has(name);
90
+ // Every base section, once: typed off `WidgetData`, so a section added there
91
+ // and not here — or named here and not there — does not compile.
92
+ const BASE_SECTIONS = {
93
+ layout: true,
94
+ session: true,
95
+ channels: true,
96
+ messages: true,
97
+ props: true,
98
+ actions: true,
99
+ settings: true,
100
+ annex: true,
101
+ locale: true,
102
+ viewer: true,
103
+ turnOrder: true,
104
+ };
105
+ /**
106
+ * The base sections, in the order the envelope declares them (R75): what
107
+ * `WidgetDecl.reads` may name, and what a widget reads when it names none.
108
+ * @experimental
109
+ */
110
+ export const WIDGET_BASE_SECTIONS = Object.freeze(Object.keys(BASE_SECTIONS));
111
+ /**
112
+ * The askers of every request kind — the marking a host enforces
113
+ * ({@link widgetRequestRefusal}). Typed off {@link WidgetRequests}, so a kind
114
+ * cannot be added without saying who may ask it.
115
+ * @experimental
116
+ */
117
+ export const WIDGET_REQUEST_ASKERS = Object.freeze({
118
+ messages: 'any',
119
+ 'open-character': 'any',
120
+ 'view-avatar': 'any',
121
+ 'view-image': 'any',
122
+ 'open-lore': 'any',
123
+ 'prompt-details': 'any',
124
+ 'inspect-run': 'any',
125
+ 'pick-turn': 'any',
126
+ 'change-sprite': 'any',
127
+ 'actions-seen': 'core',
128
+ summarize: 'core',
129
+ send: 'core',
130
+ 'attach-files': 'core',
131
+ 'remove-tray-item': 'core',
132
+ 'remove-attachment': 'core',
133
+ draft: 'core',
134
+ 'switch-persona': 'core',
135
+ 'add-persona': 'core',
136
+ 'fire-turn': 'core',
137
+ 'decide-proposal': 'core',
138
+ 'set-attribute-value': 'core',
139
+ 'set-sprite-set': 'core',
140
+ 'clear-scene-image': 'core',
141
+ 'session-entries': Object.freeze({ scope: 'lore' }),
142
+ 'set-entry-marks': 'core',
143
+ 'authors-note': 'core',
144
+ 'set-authors-note': 'core',
145
+ });
146
+ /** Every request kind — what a host checks an incoming `request` against. @experimental */
147
+ export const WIDGET_REQUEST_KINDS = Object.freeze(Object.keys(WIDGET_REQUEST_ASKERS));
148
+ /**
149
+ * Why a host must decline this request from this widget, as a sentence — or
150
+ * null when {@link WIDGET_REQUEST_ASKERS} lets it ask. `owner` is `'core'` or
151
+ * the widget's plugin id; `grants` the scopes that widget was granted, as
152
+ * BARE scopes (`'lore'`, `'session:state'`) — never the permission keys they
153
+ * are reviewed as (`'widget:lore'`), which match nothing here. Core's widgets
154
+ * hold every scope. A request is still not a grant: null means the host MAY
155
+ * answer, never that it must. Grants that are not a list — a stored string,
156
+ * whose `includes` would match a substring — grant nothing.
157
+ * @experimental
158
+ */
159
+ export function widgetRequestRefusal(kind, from) {
160
+ if (!Object.hasOwn(WIDGET_REQUEST_ASKERS, kind))
161
+ return `'${kind}' is not something a host answers`;
162
+ const askers = WIDGET_REQUEST_ASKERS[kind];
163
+ if (askers === 'any' || from.owner === 'core')
164
+ return null;
165
+ if (askers === 'core')
166
+ return `only core's own widgets ask '${kind}'`;
167
+ return Array.isArray(from.grants) && from.grants.includes(askers.scope)
168
+ ? null
169
+ : `'${kind}' reads what the '${askers.scope}' scope covers, and this widget was not granted it`;
170
+ }
171
+ /**
172
+ * 🚧 The scope a widget must hold to HEAR an event kind (R81) — a kind not
173
+ * listed is heard by every widget its channel reaches. An event about scoped
174
+ * data is scoped data: a widget that may not read the lore is not told when
175
+ * it moved. Read by {@link widgetEventHeard}, which every host delivery of
176
+ * widget events asks.
177
+ * @experimental
178
+ */
179
+ export const WIDGET_EVENT_SCOPES = Object.freeze({
180
+ 'lore:ranked': 'lore',
181
+ 'lore:marked': 'lore',
182
+ });
183
+ /**
184
+ * Is this widget told of an event of this kind? Core's widgets hold every
185
+ * scope; a plugin's hears a scoped kind only when granted its scope — as
186
+ * BARE scopes (`'lore'`), never the permission keys (`'widget:lore'`); grants
187
+ * that are not a list grant nothing (the rule {@link widgetRequestRefusal}
188
+ * holds a request to).
189
+ * @experimental
190
+ */
191
+ export function widgetEventHeard(kind, to) {
192
+ const scope = Object.hasOwn(WIDGET_EVENT_SCOPES, kind) ? WIDGET_EVENT_SCOPES[kind] : undefined;
193
+ if (!scope || to.owner === 'core')
194
+ return true;
195
+ return Array.isArray(to.grants) && to.grants.includes(scope);
196
+ }
197
+ /**
198
+ * The version of the widget contract — the verbs above and the message kinds
199
+ * that carry them.
200
+ *
201
+ * ONE number for both deliveries: native IS frame minus the iframe (ruled
202
+ * 2026-09-08), so a second clock for the in-document lane would be a second
203
+ * contract by accident. `FRAME_PROTOCOL` in `surfaces.ts` is this constant
204
+ * under the name the frame wire spells it, and the frame's `init` carries it.
205
+ * @experimental
206
+ */
207
+ export const WIDGET_PROTOCOL = 2;
208
+ //# sourceMappingURL=widgets.js.map
package/dist/wire.d.ts ADDED
@@ -0,0 +1,126 @@
1
+ /**
2
+ * Allocation and wire formatting are two jobs, and only one of them is modality-agnostic
3
+ * (16 §7).
4
+ *
5
+ * The earlier draft fused them: Assemble owned a Jinja template and published
6
+ * `assembled-context@1`, which forced that shape to mean *"a rendered string."* That is
7
+ * correct for exactly one family of connections. A chat-completion endpoint wants a
8
+ * role-tagged array; a raw completion endpoint wants one string with instruct sequences;
9
+ * ComfyUI wants prompt fields plugged into a workflow. The tell was `renderImage`
10
+ * declaring both `context: assembled-context@1` **and** `prompts: {positive, negative}` —
11
+ * it already half-admitted it did not want a rendered blob.
12
+ *
13
+ * So:
14
+ *
15
+ * - **Assemble allocates.** What fits, in what order, honouring weights and minimums, and
16
+ * recording why each block is in or out. Pure, universal, and where "why was this
17
+ * dropped" is answered. It publishes `allocated-context@1`: blocks, not prose.
18
+ * - **The Provider formats**, through a declared `wire` slot whose default comes from the
19
+ * connection's adapter metadata. Swapping Ollama for OpenAI does not re-author a spec.
20
+ *
21
+ * A slot rather than adapter-internal logic, for the reason 16 §2 already gives about the
22
+ * retrieval-strategy switch: **a declared field is visible in config, rendered in a lens
23
+ * and resolved in the receipt; logic inside a leaf is none of those.**
24
+ */
25
+ /** @experimental */
26
+ export type BlockRole = 'system' | 'user' | 'assistant' | 'tool' | 'note';
27
+ /** @experimental */
28
+ export interface ContextBlock {
29
+ id?: string;
30
+ /** Which retrieval source produced it — the axis the weights lens groups by. */
31
+ sourceKey: string;
32
+ role: BlockRole;
33
+ /** Already text by the time it reaches Assemble (16 §3b, enforced by port shapes). */
34
+ rendered: string;
35
+ /** Counted once, at render time. Allocation is then arithmetic over integers. */
36
+ tokens: number;
37
+ weight?: number;
38
+ priority?: 'low' | 'normal' | 'high' | 'always';
39
+ order?: number;
40
+ /** Position inside the history, for depth insertion (16 §5e). */
41
+ depth?: number;
42
+ included: boolean;
43
+ /**
44
+ * **The trail.** Each step appends one line — the trigger Query says which key
45
+ * matched, the rank Task says which group it won or lost and how the probability
46
+ * rolled, Assemble says whether the budget reached it.
47
+ *
48
+ * The debug panel is worth opening exactly to the extent that this is populated. A
49
+ * panel that can only say "dropped — budget" is a token counter.
50
+ */
51
+ why: string[];
52
+ }
53
+ /** @experimental */
54
+ export interface AllocatedContext {
55
+ blocks: ContextBlock[];
56
+ allocation: {
57
+ budget: number;
58
+ used: number;
59
+ droppedTokens: number;
60
+ policy: 'oldest-first' | 'lowest-weight' | string;
61
+ /** True when a template engine could not analyse itself, so the margin widened. */
62
+ estimateExact?: boolean;
63
+ };
64
+ }
65
+ /** @experimental */
66
+ export declare const isAllocatedContext: (v: unknown) => v is AllocatedContext;
67
+ /** @experimental */
68
+ export declare const included: (c: AllocatedContext) => ContextBlock[];
69
+ /** @experimental */
70
+ export interface WireFormat {
71
+ id: string;
72
+ label: string;
73
+ /** What actually goes on the wire. */
74
+ format(ctx: AllocatedContext, opts?: Record<string, unknown>): unknown;
75
+ /**
76
+ * Tokens the scaffolding adds — role markers, instruct sequences, JSON overhead.
77
+ * Declared rather than measured after the fact, so Assemble can allocate against a
78
+ * **ceiling** and the answer to "will this overspend" is provable (16 §7).
79
+ */
80
+ overhead(ctx: AllocatedContext, count: (s: string) => number): number;
81
+ }
82
+ /** @experimental */
83
+ export declare function defineWireFormat(w: WireFormat): WireFormat;
84
+ /** @experimental */
85
+ export declare const getWireFormat: (id: string) => WireFormat | undefined;
86
+ /** @experimental */
87
+ export declare const allWireFormats: () => WireFormat[];
88
+ /** @internal */
89
+ export declare function _clearWireFormats(): void;
90
+ /** @experimental */
91
+ export declare function formatWith(id: string, ctx: AllocatedContext, opts?: Record<string, unknown>): unknown;
92
+ /** Chat completion: the role-tagged array. @experimental */
93
+ export declare const messages: WireFormat;
94
+ /** Text completion, ChatML sequences. @experimental */
95
+ export declare const chatml: WireFormat;
96
+ /** Text completion, Alpaca-style. @experimental */
97
+ export declare const alpaca: WireFormat;
98
+ /** Everything joined, no scaffolding. The reference implementation of zero overhead. @experimental */
99
+ export declare const plainWire: WireFormat;
100
+ /**
101
+ * Prompt **fields**, for a Provider that plugs values into a workflow rather than sending
102
+ * prose — image generation being the case that exposed the whole problem.
103
+ * @experimental
104
+ */
105
+ export declare const fields: WireFormat;
106
+ /** @experimental */
107
+ export interface WireMeasure {
108
+ format: string;
109
+ payload: unknown;
110
+ /** Blocks + declared scaffolding. The figure Assemble allocated against. */
111
+ tokens: number;
112
+ blockTokens: number;
113
+ overheadTokens: number;
114
+ /** Set when the formed payload exceeds what the budget allowed. */
115
+ overBudgetBy?: number;
116
+ }
117
+ /**
118
+ * Format once and measure once, at the pre-call substrate.
119
+ *
120
+ * The allocation loop must never re-render or re-count: count each block at render time,
121
+ * allocate over integers, format exactly once. Anything else has a performance cliff at
122
+ * precisely the moment a user's context is biggest.
123
+ * @experimental
124
+ */
125
+ export declare function measureWire(formatId: string, ctx: AllocatedContext, count: (s: string) => number, available?: number, opts?: Record<string, unknown>): WireMeasure;
126
+ //# sourceMappingURL=wire.d.ts.map
package/dist/wire.js ADDED
@@ -0,0 +1,140 @@
1
+ /**
2
+ * Allocation and wire formatting are two jobs, and only one of them is modality-agnostic
3
+ * (16 §7).
4
+ *
5
+ * The earlier draft fused them: Assemble owned a Jinja template and published
6
+ * `assembled-context@1`, which forced that shape to mean *"a rendered string."* That is
7
+ * correct for exactly one family of connections. A chat-completion endpoint wants a
8
+ * role-tagged array; a raw completion endpoint wants one string with instruct sequences;
9
+ * ComfyUI wants prompt fields plugged into a workflow. The tell was `renderImage`
10
+ * declaring both `context: assembled-context@1` **and** `prompts: {positive, negative}` —
11
+ * it already half-admitted it did not want a rendered blob.
12
+ *
13
+ * So:
14
+ *
15
+ * - **Assemble allocates.** What fits, in what order, honouring weights and minimums, and
16
+ * recording why each block is in or out. Pure, universal, and where "why was this
17
+ * dropped" is answered. It publishes `allocated-context@1`: blocks, not prose.
18
+ * - **The Provider formats**, through a declared `wire` slot whose default comes from the
19
+ * connection's adapter metadata. Swapping Ollama for OpenAI does not re-author a spec.
20
+ *
21
+ * A slot rather than adapter-internal logic, for the reason 16 §2 already gives about the
22
+ * retrieval-strategy switch: **a declared field is visible in config, rendered in a lens
23
+ * and resolved in the receipt; logic inside a leaf is none of those.**
24
+ */
25
+ import { refuseUnlessIdentical } from './hash.js';
26
+ /** @experimental */
27
+ export const isAllocatedContext = (v) => !!v && typeof v === 'object' && Array.isArray(v.blocks);
28
+ /** @experimental */
29
+ export const included = (c) => c.blocks.filter((b) => b.included);
30
+ const formats = new Map();
31
+ /** @experimental */
32
+ export function defineWireFormat(w) {
33
+ const existing = formats.get(w.id);
34
+ // Display text for the same reason a template engine's is: the picker shows
35
+ // `label`, the wire carries `format`.
36
+ if (existing)
37
+ refuseUnlessIdentical(existing, w, `duplicate wire format id: ${w.id}`, {
38
+ display: ['label'],
39
+ });
40
+ formats.set(w.id, w);
41
+ return w;
42
+ }
43
+ /** @experimental */
44
+ export const getWireFormat = (id) => formats.get(id);
45
+ /** @experimental */
46
+ export const allWireFormats = () => [...formats.values()];
47
+ /** @internal */
48
+ export function _clearWireFormats() {
49
+ formats.clear();
50
+ }
51
+ /** @experimental */
52
+ export function formatWith(id, ctx, opts) {
53
+ const w = formats.get(id);
54
+ if (!w) {
55
+ throw new Error(`no wire format registered for '${id}'. Available: ${allWireFormats().map((x) => x.id).join(', ') || 'none'}. ` +
56
+ `A wire format ships with the adapter that declares it — this usually means the connection's plugin is disabled.`);
57
+ }
58
+ return w.format(ctx, opts);
59
+ }
60
+ // ── Core formats ────────────────────────────────────────────────────────────
61
+ const roleFor = (b) => (b.role === 'note' ? 'system' : b.role);
62
+ /** Chat completion: the role-tagged array. @experimental */
63
+ export const messages = defineWireFormat({
64
+ id: 'core:wire/messages@1',
65
+ label: 'Chat completion (messages array)',
66
+ format: (ctx) => included(ctx).map((b) => ({ role: roleFor(b), content: b.rendered })),
67
+ // Per message: the role key, the content key and JSON punctuation. Declared, not guessed.
68
+ overhead: (ctx) => included(ctx).length * 4 + 2,
69
+ });
70
+ /** Text completion, ChatML sequences. @experimental */
71
+ export const chatml = defineWireFormat({
72
+ id: 'core:wire/chatml@1',
73
+ label: 'Text completion (ChatML)',
74
+ format: (ctx) => included(ctx)
75
+ .map((b) => `<|im_start|>${roleFor(b)}\n${b.rendered}<|im_end|>`)
76
+ .join('\n') + '\n<|im_start|>assistant\n',
77
+ overhead: (ctx, count) => included(ctx).length * count('<|im_start|>assistant\n<|im_end|>\n') + count('<|im_start|>assistant\n'),
78
+ });
79
+ /** Text completion, Alpaca-style. @experimental */
80
+ export const alpaca = defineWireFormat({
81
+ id: 'core:wire/alpaca@1',
82
+ label: 'Text completion (Alpaca)',
83
+ format: (ctx) => {
84
+ const b = included(ctx);
85
+ const sys = b.filter((x) => roleFor(x) === 'system').map((x) => x.rendered);
86
+ const rest = b.filter((x) => roleFor(x) !== 'system').map((x) => x.rendered);
87
+ return [...sys, '### Instruction:', ...rest, '### Response:'].join('\n\n');
88
+ },
89
+ overhead: (_ctx, count) => count('### Instruction:\n\n### Response:\n\n'),
90
+ });
91
+ /** Everything joined, no scaffolding. The reference implementation of zero overhead. @experimental */
92
+ export const plainWire = defineWireFormat({
93
+ id: 'core:wire/plain@1',
94
+ label: 'Plain concatenation',
95
+ format: (ctx) => included(ctx).map((b) => b.rendered).join('\n'),
96
+ overhead: (ctx, count) => Math.max(0, included(ctx).length - 1) * count('\n'),
97
+ });
98
+ /**
99
+ * Prompt **fields**, for a Provider that plugs values into a workflow rather than sending
100
+ * prose — image generation being the case that exposed the whole problem.
101
+ * @experimental
102
+ */
103
+ export const fields = defineWireFormat({
104
+ id: 'core:wire/fields@1',
105
+ label: 'Prompt fields (positive / negative)',
106
+ format: (ctx) => {
107
+ const b = included(ctx);
108
+ return {
109
+ positive: b.filter((x) => x.role !== 'note').map((x) => x.rendered).join(', '),
110
+ negative: b.filter((x) => x.role === 'note').map((x) => x.rendered).join(', '),
111
+ };
112
+ },
113
+ overhead: (ctx, count) => Math.max(0, included(ctx).length - 1) * count(', '),
114
+ });
115
+ /**
116
+ * Format once and measure once, at the pre-call substrate.
117
+ *
118
+ * The allocation loop must never re-render or re-count: count each block at render time,
119
+ * allocate over integers, format exactly once. Anything else has a performance cliff at
120
+ * precisely the moment a user's context is biggest.
121
+ * @experimental
122
+ */
123
+ export function measureWire(formatId, ctx, count, available, opts) {
124
+ const w = formats.get(formatId);
125
+ if (!w)
126
+ throw new Error(`no wire format registered for '${formatId}'`);
127
+ const payload = w.format(ctx, opts);
128
+ const blockTokens = included(ctx).reduce((n, b) => n + b.tokens, 0);
129
+ const overheadTokens = w.overhead(ctx, count);
130
+ const tokens = blockTokens + overheadTokens;
131
+ return {
132
+ format: formatId,
133
+ payload,
134
+ tokens,
135
+ blockTokens,
136
+ overheadTokens,
137
+ overBudgetBy: typeof available === 'number' && tokens > available ? tokens - available : undefined,
138
+ };
139
+ }
140
+ //# sourceMappingURL=wire.js.map
@@ -0,0 +1,150 @@
1
+ /**
2
+ * World Info parity — testing the claim in 13 §7i.
3
+ *
4
+ * The competitive assessment asserts that every SillyTavern World Info feature "maps into
5
+ * the existing model as params or template logic, not as new mechanisms." That was an
6
+ * untested claim about the most competitively important feature in the product, so this
7
+ * module implements them and the tests check whether it held.
8
+ *
9
+ * Verdict, recorded honestly at the bottom of this file.
10
+ * @experimental
11
+ */
12
+ export interface LoreEntry {
13
+ id: string;
14
+ title: string;
15
+ content: string;
16
+ keys: string[];
17
+ /** Secondary filter with a logic operator, as ST has. */
18
+ secondary?: {
19
+ op: 'AND_ANY' | 'AND_ALL' | 'NOT_ANY' | 'NOT_ALL';
20
+ keys: string[];
21
+ };
22
+ useRegex?: boolean;
23
+ /** Always inserted, budget permitting — ST's "constant". */
24
+ constant?: boolean;
25
+ /** 0..1. ST rolls this unreproducibly; here it rolls against the run seed. */
26
+ probability?: number;
27
+ /** Competing entries share a label; the highest weight (or order) wins. */
28
+ group?: string;
29
+ groupWeight?: number;
30
+ /** Larger order sits closer to the end of the context. */
31
+ order?: number;
32
+ /** Where it goes: a named position, or a depth into the chat history. */
33
+ position?: 'before_char' | 'after_char' | 'author_note' | {
34
+ atDepth: number;
35
+ };
36
+ /**
37
+ * ⚠ **The one real parity gap** (13 §7i). Depth positioning is expressed in the
38
+ * assembly template, not by a node or a shape — but the template has to have
39
+ * something to compare against, and **SP lorebook entries carry no `depth` today.**
40
+ *
41
+ * This field is the whole fix: an entry-schema addition in the lorebook model, not
42
+ * architecture. "Feature missing" and "architecture can't express it" are different
43
+ * sizes of problem and only the first was ever true. See 16 §5e and use case 41.
44
+ */
45
+ depth?: number;
46
+ /** May this entry activate others by mentioning their keys? */
47
+ recursable?: boolean;
48
+ preventRecursion?: boolean;
49
+ }
50
+ /** @experimental */
51
+ export interface ScanParams {
52
+ scanDepth: number;
53
+ caseSensitive: boolean;
54
+ recursionDepth: number;
55
+ useRegex: boolean;
56
+ }
57
+ /**
58
+ * Activation, including bounded recursion.
59
+ *
60
+ * Recursion lives *inside* the Query hook's opaque interior (01 §12.3) and is bounded by a
61
+ * declared param — so it needs no pipeline-level construct and cannot become an unbounded
62
+ * loop. This is the part of the parity claim that held cleanly.
63
+ * @experimental
64
+ */
65
+ export declare function activate(entries: LoreEntry[], scanText: string[], p: ScanParams): {
66
+ entry: LoreEntry;
67
+ depth: number;
68
+ }[];
69
+ /** Probability, rolled against the run seed — so it replays, which ST's cannot. @experimental */
70
+ export declare function rollProbability(hits: {
71
+ entry: LoreEntry;
72
+ depth: number;
73
+ }[], random: () => number): {
74
+ kept: LoreEntry[];
75
+ rolledOut: string[];
76
+ };
77
+ /**
78
+ * Inclusion groups: competing entries share a label, and one wins by group weight, with
79
+ * insertion order as the deterministic tiebreak.
80
+ *
81
+ * This is ranking, so it belongs in the rank Task (16 §5c) — no new mechanism.
82
+ * @experimental
83
+ */
84
+ export declare function resolveGroups(entries: LoreEntry[], random: () => number): {
85
+ kept: LoreEntry[];
86
+ lost: string[];
87
+ };
88
+ /** @experimental */
89
+ export interface PositionedItem {
90
+ id: string;
91
+ rendered: string;
92
+ order: number;
93
+ position: LoreEntry['position'];
94
+ weight: number;
95
+ priority: 'always' | 'high' | 'normal' | 'low';
96
+ }
97
+ /**
98
+ * Depth positioning **in a Task** — one of two valid places to do it.
99
+ *
100
+ * ⚠ RETRACTION. An earlier version of this file claimed depth positioning "didn't map" and
101
+ * needed a shape change. That was wrong. **Depth is a context-template concern**, and the
102
+ * assembly template expresses it directly:
103
+ *
104
+ * ```jinja
105
+ * {% for m in messages %}{% set d = loop.revindex %}
106
+ * {% for l in lore %}{% if l.depth == d %}{{ l.rendered }}{% endif %}{% endfor %}
107
+ * {{ m.rendered }}
108
+ * {% endfor %}
109
+ * ```
110
+ *
111
+ * That is tested end to end in use case 41. Nothing about `context-candidates` changes —
112
+ * it already carried `items[]`, which is all the loop needs. The only real requirement is
113
+ * the obvious one: a Query that flattens its messages into a single opaque string forecloses
114
+ * it, so history reaches the template as a list. That is guidance, not a schema change.
115
+ *
116
+ * This function remains as the Task-side alternative, for authors who would rather compute
117
+ * placement than express it in a template.
118
+ * @experimental
119
+ */
120
+ export declare function assembleWithPositions(history: PositionedItem[], lore: PositionedItem[], budget: number, costOf: (s: string) => number): {
121
+ text: string;
122
+ included: string[];
123
+ dropped: string[];
124
+ };
125
+ /**
126
+ * ── Verdict on 13 §7i's claim ──────────────────────────────────────────────
127
+ *
128
+ * **Seven of seven mapped with no new mechanism.**
129
+ *
130
+ * · regex keys, logic operators, scan depth → params on the trigger Query
131
+ * · recursion → bounded scan inside the Query's interior
132
+ * · constants → priority 'always', honoured before budget
133
+ * · probability → the run seed, and replayable unlike ST's
134
+ * · inclusion groups + group weight → the rank Task, which already existed
135
+ * · insertion order → sort key, or template ordering
136
+ * · positional insertion at chat depth → the assembly template, via a loop over
137
+ * messages with the depth captured by `set`
138
+ *
139
+ * The claim held. An earlier draft of this file reported a shape change was needed; that was
140
+ * my error, corrected after Jody pointed out depth is a templating concern.
141
+ *
142
+ * ── The real parity gap is elsewhere ───────────────────────────────────────
143
+ *
144
+ * **SP's lorebook entries have no `depth` field today.** The pipeline can position by depth
145
+ * the moment an entry carries one — so the work is an entry-schema addition in the lorebook
146
+ * model, not anything in the pipeline architecture. Worth stating precisely, because
147
+ * "positional insertion is missing" and "the architecture can't express it" are very
148
+ * different problems and only the first one is true.
149
+ */
150
+ //# sourceMappingURL=worldinfo.d.ts.map