@panticonic/pi-chord 0.99.2-vibestudio.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.
Files changed (120) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +264 -0
  3. package/SOURCE.json +8858 -0
  4. package/dist/api.d.ts +20 -0
  5. package/dist/api.d.ts.map +1 -0
  6. package/dist/api.js +77 -0
  7. package/dist/api.js.map +1 -0
  8. package/dist/bundler.d.ts +6 -0
  9. package/dist/bundler.d.ts.map +1 -0
  10. package/dist/bundler.js +3 -0
  11. package/dist/bundler.js.map +1 -0
  12. package/dist/context/index.d.ts +24 -0
  13. package/dist/context/index.d.ts.map +1 -0
  14. package/dist/context/index.js +97 -0
  15. package/dist/context/index.js.map +1 -0
  16. package/dist/delta/apply-immutable-trusted.d.ts +4 -0
  17. package/dist/delta/apply-immutable-trusted.d.ts.map +1 -0
  18. package/dist/delta/apply-immutable-trusted.js +127 -0
  19. package/dist/delta/apply-immutable-trusted.js.map +1 -0
  20. package/dist/delta/diff.d.ts +5 -0
  21. package/dist/delta/diff.d.ts.map +1 -0
  22. package/dist/delta/diff.js +433 -0
  23. package/dist/delta/diff.js.map +1 -0
  24. package/dist/delta/draft.d.ts +5 -0
  25. package/dist/delta/draft.d.ts.map +1 -0
  26. package/dist/delta/draft.js +2 -0
  27. package/dist/delta/draft.js.map +1 -0
  28. package/dist/delta/index.d.ts +111 -0
  29. package/dist/delta/index.d.ts.map +1 -0
  30. package/dist/delta/index.js +648 -0
  31. package/dist/delta/index.js.map +1 -0
  32. package/dist/delta/revision-validator.d.ts +7 -0
  33. package/dist/delta/revision-validator.d.ts.map +1 -0
  34. package/dist/delta/revision-validator.js +71 -0
  35. package/dist/delta/revision-validator.js.map +1 -0
  36. package/dist/delta/tracker.d.ts +26 -0
  37. package/dist/delta/tracker.d.ts.map +1 -0
  38. package/dist/delta/tracker.js +2069 -0
  39. package/dist/delta/tracker.js.map +1 -0
  40. package/dist/facets/host.d.ts +12 -0
  41. package/dist/facets/host.d.ts.map +1 -0
  42. package/dist/facets/host.js +763 -0
  43. package/dist/facets/host.js.map +1 -0
  44. package/dist/facets/loader.d.ts +3 -0
  45. package/dist/facets/loader.d.ts.map +1 -0
  46. package/dist/facets/loader.js +5 -0
  47. package/dist/facets/loader.js.map +1 -0
  48. package/dist/index.d.ts +12 -0
  49. package/dist/index.d.ts.map +1 -0
  50. package/dist/index.js +10 -0
  51. package/dist/index.js.map +1 -0
  52. package/dist/json.d.ts +10 -0
  53. package/dist/json.d.ts.map +1 -0
  54. package/dist/json.js +124 -0
  55. package/dist/json.js.map +1 -0
  56. package/dist/node/bundle-loader.d.ts +30 -0
  57. package/dist/node/bundle-loader.d.ts.map +1 -0
  58. package/dist/node/bundle-loader.js +377 -0
  59. package/dist/node/bundle-loader.js.map +1 -0
  60. package/dist/node/bundle.d.ts +26 -0
  61. package/dist/node/bundle.d.ts.map +1 -0
  62. package/dist/node/bundle.js +183 -0
  63. package/dist/node/bundle.js.map +1 -0
  64. package/dist/node/manifest.d.ts +36 -0
  65. package/dist/node/manifest.d.ts.map +1 -0
  66. package/dist/node/manifest.js +6 -0
  67. package/dist/node/manifest.js.map +1 -0
  68. package/dist/node/package.d.ts +15 -0
  69. package/dist/node/package.d.ts.map +1 -0
  70. package/dist/node/package.js +199 -0
  71. package/dist/node/package.js.map +1 -0
  72. package/dist/node.d.ts +5 -0
  73. package/dist/node.d.ts.map +1 -0
  74. package/dist/node.js +3 -0
  75. package/dist/node.js.map +1 -0
  76. package/dist/services/consumer.d.ts +11 -0
  77. package/dist/services/consumer.d.ts.map +1 -0
  78. package/dist/services/consumer.js +585 -0
  79. package/dist/services/consumer.js.map +1 -0
  80. package/dist/services/errors.d.ts +8 -0
  81. package/dist/services/errors.d.ts.map +1 -0
  82. package/dist/services/errors.js +22 -0
  83. package/dist/services/errors.js.map +1 -0
  84. package/dist/services/handle.d.ts +15 -0
  85. package/dist/services/handle.d.ts.map +1 -0
  86. package/dist/services/handle.js +101 -0
  87. package/dist/services/handle.js.map +1 -0
  88. package/dist/services/instances.d.ts +26 -0
  89. package/dist/services/instances.d.ts.map +1 -0
  90. package/dist/services/instances.js +140 -0
  91. package/dist/services/instances.js.map +1 -0
  92. package/dist/services/loopback.d.ts +5 -0
  93. package/dist/services/loopback.d.ts.map +1 -0
  94. package/dist/services/loopback.js +15 -0
  95. package/dist/services/loopback.js.map +1 -0
  96. package/dist/services/provider.d.ts +37 -0
  97. package/dist/services/provider.d.ts.map +1 -0
  98. package/dist/services/provider.js +521 -0
  99. package/dist/services/provider.js.map +1 -0
  100. package/dist/services/state-codec.d.ts +15 -0
  101. package/dist/services/state-codec.d.ts.map +1 -0
  102. package/dist/services/state-codec.js +133 -0
  103. package/dist/services/state-codec.js.map +1 -0
  104. package/dist/services/state-internals.d.ts +13 -0
  105. package/dist/services/state-internals.d.ts.map +1 -0
  106. package/dist/services/state-internals.js +10 -0
  107. package/dist/services/state-internals.js.map +1 -0
  108. package/dist/services/state.d.ts +28 -0
  109. package/dist/services/state.d.ts.map +1 -0
  110. package/dist/services/state.js +397 -0
  111. package/dist/services/state.js.map +1 -0
  112. package/dist/services/wire.d.ts +63 -0
  113. package/dist/services/wire.d.ts.map +1 -0
  114. package/dist/services/wire.js +186 -0
  115. package/dist/services/wire.js.map +1 -0
  116. package/dist/types.d.ts +273 -0
  117. package/dist/types.d.ts.map +1 -0
  118. package/dist/types.js +2 -0
  119. package/dist/types.js.map +1 -0
  120. package/package.json +62 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Mario Zechner
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,264 @@
1
+ # @panticonic/pi-chord
2
+
3
+ Chord is an application-composition runtime for systems assembled from
4
+ plugins/extensions. It provides facets, services, replicated state, and a
5
+ pluggable remote-service boundary. It is developed as a standalone package in
6
+ the Pi monorepo, but it is not a Pi package: it does not depend on any other Pi
7
+ workspace package and can be used by unrelated applications.
8
+
9
+ ## What Chord is for
10
+
11
+ A single application feature may need to run in several environments: for
12
+ example, an agent worker, a terminal UI, and a remote WebUI. Chord provides the
13
+ generic machinery to write such extensions in a way that is both delightful for
14
+ humans as well as agents.
15
+
16
+ The design has a few connected pieces:
17
+
18
+ - **Plugins** are synchronous setup units that declare the services they provide
19
+ and require. After every plugin has declared its shape, a host validates the
20
+ complete dependency graph, binds services, activates providers before consumers,
21
+ and disposes resources in reverse dependency order. These units are called
22
+ *facets*.
23
+
24
+ - **Facets** are parts of a plugin. Each facet is bundled up separately and runs
25
+ in the process or environment where it's supposed to run. You can use facets
26
+ to split a plugin into separate pieces that need to be loaded into different
27
+ processes and environments (think backend, browser, TUI etc.)
28
+
29
+ - **Services** are typed, stable tokens with either one provider (**singleton**)
30
+ or dynamic keyed instances (**keyed**). A service can be process-local, with
31
+ an unrestricted JavaScript contract, or remotely exposable. Consumers retain a
32
+ stable facade while a provider disconnects or is replaced.
33
+
34
+ - **Replicated state** exposes authoritative state to local and remote
35
+ connected consumers. Producers publish atomic overlay transactions with
36
+ `change(context, callback)`; consumers receive complete immutable values. Draft
37
+ proxies exist only during the callback and become unusable afterward. Preparation
38
+ materializes a structurally shared immutable candidate and one exact decoded
39
+ operation batch, while each remote client/state stream owns independent path-codec
40
+ state. Replicas become unready on disconnect or replacement until rehydrated.
41
+
42
+ - **Delta tracking** records and coalesces operations over tracked plain JSON.
43
+ It preserves common string and array operations, supports durable base
44
+ batches, and validates untrusted operations as they are applied. Batches
45
+ guarantee convergence but are not canonical or necessarily minimal.
46
+
47
+ - **Remote service sources** advertise services available outside a facet host
48
+ and open bindings for the services its facets require. Bindings carry logical
49
+ calls and subscriptions through an application-supplied adapter. Chord
50
+ requires strict-JSON arguments, results, snapshots, updates, and catalogues,
51
+ but does not prescribe framing, routing, transport, or an application wire
52
+ envelope. `JsonRepresentation<T>` derives a wire-safe type for application data
53
+ with unknown payloads, while `isJsonValue()` validates received values at an
54
+ adapter boundary. Symmetric RPC peers are planned as one optional
55
+ implementation of this boundary.
56
+
57
+ - **Context** Chord provides a Go-like context system for cancellation and
58
+ invocation-scoped application values. Applications can carry permissions or
59
+ telemetry through those values without Chord depending on either.
60
+
61
+ The current runtime exports service tokens, singleton and keyed providers,
62
+ remote bindings, replicated state, facet hosts, and facet loaders from
63
+ `@panticonic/pi-chord`. Import public types and general runtime APIs from the
64
+ package root. Context constants and functions live in
65
+ `@panticonic/pi-chord/context` because their generic names should not pollute
66
+ the root API.
67
+ Chord-owned identifiers use the `chord.*` namespace and its reserved service
68
+ prefix is `$chord.*`.
69
+
70
+ ## Remote service adapters
71
+
72
+ Chord owns its transport-independent service wire grammar. Consumer adapters
73
+ use `createServiceCatalogueCall()`, `createServiceSubscribeCall()`, and
74
+ `createServiceUnsubscribeCall()` for `$chord.service` control calls.
75
+ `createRemoteServiceEndpoint()` handles those calls for one provider consumer,
76
+ including subscription activation and cleanup. `parseServiceCall()`,
77
+ `parseServiceCatalogue()`, and the decoded/wire snapshot and update parsers
78
+ validate Chord semantics after an adapter has established a strict-JSON
79
+ boundary. `RemoteServiceErrorCode` and `REMOTE_SERVICE_ERROR_CODES` define the
80
+ service errors that may cross that boundary.
81
+
82
+ Replicated state operations use one `createServiceStateEncoder()` at the
83
+ provider side and one `createServiceStateDecoder()` at the consumer side for
84
+ each subscription. Those registries create an independent Delta path dictionary
85
+ for every instance/member state and reset it on replacement, unavailability,
86
+ close, or fresh hydration. Applications may place these values inside any
87
+ routing, request, response, or event envelope; Chord does not prescribe that
88
+ outer protocol.
89
+
90
+ Provider subscriptions atomically capture a snapshot and buffer subsequent
91
+ updates until activation. Activation and reentrant publication use the same FIFO.
92
+ The provider retains at most 100 pending updates per subscription, excluding the
93
+ running delivery. Adding update 101 replaces the entire pending queue with
94
+ `{ type: "reset", snapshot }`: a current full subscription snapshot whose state
95
+ members contain `[["r", value]]` and their new sequence baselines. It also captures
96
+ current instance membership, so discarded spawn/close/replacement events cannot
97
+ leave stale instances behind. Live keyed generations retain their existing handles.
98
+ The reset carries the context of the publication that triggered overflow.
99
+
100
+ Consumers and codecs must handle this explicit reset before accepting subsequent
101
+ ordinary deltas. A root operation in an ordinary `state` update does **not** permit
102
+ a sequence gap. Resets restart the subscription's path dictionaries, and later
103
+ deltas must be contiguous from each reset baseline. Transport adapters must
104
+ preserve snapshot/reset/update order; they must not drop encoded delta batches or
105
+ assume their own asynchronous queues are bounded by the provider's queue.
106
+
107
+ ## Tracking JSON deltas
108
+
109
+ Import the standalone transactional tracker from `@panticonic/pi-chord/delta`:
110
+
111
+ ```ts
112
+ import { applyImmutable, track } from "@panticonic/pi-chord/delta";
113
+
114
+ const tracker = track({ output: "", count: 0 });
115
+ const change = tracker.beginChange();
116
+ change.state.output += "done\n";
117
+ change.state.count += 1;
118
+ const prepared = change.prepare();
119
+
120
+ tracker.adopt(prepared);
121
+ const replica = applyImmutable(prepared.base, prepared.ops);
122
+ ```
123
+
124
+ `tracker.value` is always the latest adopted immutable revision. Preparation does
125
+ not change authority; adoption validates the preparation and swaps the root pointer.
126
+ Assigned containers are copied by value and unchanged subtrees may be shared between
127
+ revisions.
128
+
129
+ The tracker uses trusted immutable ownership rather than defensive copying or
130
+ freezing. `track(initial)`, `prepareReplace(value)`, `replicatedState(initial)`, and
131
+ `replace(context, value)` take ownership of alias-free strict-JSON roots without
132
+ walking them. Callers must not mutate transferred or published data. Values placed
133
+ through drafts are already copied, so that walk also rejects non-strict JSON before
134
+ the draft changes. Published values are not frozen. In-process loopback consumers
135
+ may share their containers with the provider; mutating a consumed value violates
136
+ the contract and can corrupt authority. Clone or serialize at any mutable trust
137
+ boundary.
138
+
139
+ Replicated state provides the same model through a callback:
140
+
141
+ ```ts
142
+ const initial = { output: "", count: 0 };
143
+ const status = env.replicatedState(initial); // transfers ownership of initial
144
+ status.change(context, (draft) => {
145
+ draft.output += "done\n";
146
+ draft.count += 1;
147
+ });
148
+ ```
149
+
150
+ A successful `change()` publishes exactly one atomic revision. If its callback
151
+ throws, the original value and sequence remain unchanged. Draft handles become
152
+ unusable when the callback returns. Chord emits string append and front-truncate
153
+ operations, array splices and permutations, sets, and deletes; large edit sets may
154
+ fold into a complete replacement. Remote connection plumbing encodes each batch
155
+ independently for every client/state pairing.
156
+
157
+ ### Public state subscriptions
158
+
159
+ `state.subscribe(async (value, context, delivery) => { ... })` serializes callbacks
160
+ independently for each subscription. Hydration starts immediately when a value is
161
+ available, and its returned promise must settle before updates start. Synchronous
162
+ callbacks still run synchronously. Read the captured `value` inside an asynchronous
163
+ callback: `state.value` may already refer to a later revision.
164
+
165
+ Each subscription retains at most 100 pending complete-value deliveries, excluding
166
+ the running callback. On overflow, only the newest pending value, context, and
167
+ delivery metadata are retained; a not-yet-started initial hydration is preserved.
168
+ Thus public delivery sequences may skip. This is a frame-count policy, not a byte
169
+ limit. Internal exact-operation subscriptions remain synchronous and receive every
170
+ revision, independently of slow public callbacks.
171
+
172
+ The returned unsubscribe function immediately discards pending work and prevents
173
+ new callbacks. It neither aborts nor waits for the running callback. Synchronous
174
+ throws and promise rejections are observed, reported, and do not stop other
175
+ subscriptions or subsequent callbacks. Attached sources and remote bindings use
176
+ their `onError` handler; local mutable states (and attached sources without a
177
+ handler) report failures by throwing in a microtask. Unsubscribing does not hide a
178
+ later rejection from the running callback.
179
+
180
+ The standalone [Delta guide](src/delta/README.md) defines the complete ownership,
181
+ lifecycle, operation, and replica contracts.
182
+
183
+ ## Bundling and loading facets
184
+
185
+ `@panticonic/pi-chord/bundler` uses esbuild to turn ESM or TypeScript application
186
+ entries into independent, content-addressed CommonJS files. The package-level API
187
+ reads plugin identity and build configuration from `package.json`, then applies
188
+ facet path conventions supplied by the host application:
189
+
190
+ ```json
191
+ {
192
+ "name": "@example/my-plugin",
193
+ "version": "1.0.0",
194
+ "type": "module",
195
+ "peerDependencies": {
196
+ "@panticonic/pi-chord": "^0.84.4"
197
+ },
198
+ "chord": {
199
+ "facets": {
200
+ "worker": "./src/custom-worker.ts",
201
+ "presentation": false
202
+ }
203
+ }
204
+ }
205
+ ```
206
+
207
+ ```ts
208
+ import { bundleFacetPackage } from "@panticonic/pi-chord/bundler";
209
+
210
+ await bundleFacetPackage({
211
+ packagePath: "/path/to/my-plugin",
212
+ outdir: "/application-owned/plugin-builds/my-plugin",
213
+ defaultFacets: {
214
+ worker: "src/worker.ts",
215
+ presentation: "src/presentation.ts",
216
+ },
217
+ });
218
+ ```
219
+
220
+ Existing conventional files become entries unless `chord.facets` overrides or
221
+ disables them. Peer dependencies are externalized and resolved against the host
222
+ when loading. Chord never installs dependencies or runs package lifecycle
223
+ scripts. `bundleFacets()` remains available as the lower-level API for callers
224
+ that already have explicit plugin identity and entry mappings.
225
+
226
+ The output directory contains one `.cjs` file per entry plus
227
+ `chord-facets.json`. Load one application-selected entry through the Node-only
228
+ loader:
229
+
230
+ ```ts
231
+ import { createFacetBundleLoader } from "@panticonic/pi-chord/node";
232
+
233
+ const loader = createFacetBundleLoader({
234
+ manifestPath: "/application-owned/plugin-builds/my-plugin/chord-facets.json",
235
+ entry: "worker",
236
+ resolveExternal: (specifier) => import.meta.resolve(specifier),
237
+ });
238
+ const loaded = await loader.load();
239
+ ```
240
+
241
+ Each `load()` verifies SHA-256 integrity and compiles the CommonJS body directly
242
+ with `node:vm` instead of putting the plugin into Node's CommonJS or ESM module
243
+ cache. Externals are resolved by the host and loaded through a restricted
244
+ `require`; esbuild lowers dynamic imports so they use the same path. Disposing a
245
+ retired generation releases the loader's facet references, making its compiled
246
+ code eligible for garbage collection once plugin-owned resources are also gone.
247
+
248
+ For transport to another Node host, `readFacetBundleArtifact()` packages one
249
+ verified manifest entry with its source, and `createFacetBundleArtifactLoader()`
250
+ materializes fresh temporary generations while resolving externals against the
251
+ receiving host.
252
+
253
+ To reload, load a candidate, pass its facets to `FacetHost.reload()`, dispose the
254
+ candidate on failure, and dispose the retired `LoadedFacets` only after a
255
+ successful cutover. The host activates and validates the candidate while the
256
+ currently active providers remain routed, then replaces each singleton directly
257
+ without an unavailable interval. Stable service handles therefore do not become
258
+ disconnected during an ordinary reload. Keyed instances
259
+ remain incarnation-specific and replacements receive fresh generations. The
260
+ bundler writes a complete temporary directory before replacing the previous
261
+ output, so loaders do not observe partially built generations.
262
+
263
+ See [PLANNING.md](PLANNING.md) for the broader RPC and generation-loading
264
+ architecture.