psionic 0.3.2 → 0.3.3

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 (84) hide show
  1. package/adapters/reconnect.d.mts +10 -0
  2. package/adapters/reconnect.mjs +2 -0
  3. package/adapters/reconnect.mjs.map +1 -0
  4. package/adapters/resend.d.mts +13 -0
  5. package/adapters/resend.mjs +2 -0
  6. package/adapters/resend.mjs.map +1 -0
  7. package/adapters/socket.d.mts +14 -0
  8. package/adapters/socket.mjs +3 -0
  9. package/adapters/socket.mjs.map +1 -0
  10. package/adapters/websocket.d.mts +21 -0
  11. package/adapters/websocket.mjs +2 -0
  12. package/adapters/websocket.mjs.map +1 -0
  13. package/adapters/webworker.d.mts +8 -0
  14. package/adapters/webworker.mjs +2 -0
  15. package/adapters/webworker.mjs.map +1 -0
  16. package/codecs/cbor.d.mts +12 -0
  17. package/codecs/cbor.mjs +2 -0
  18. package/codecs/cbor.mjs.map +1 -0
  19. package/codecs/psionic.d.mts +12 -0
  20. package/codecs/psionic.mjs +2 -0
  21. package/codecs/psionic.mjs.map +1 -0
  22. package/package.json +42 -24
  23. package/psionic.d.mts +203 -0
  24. package/psionic.mjs +2 -0
  25. package/psionic.mjs.map +1 -0
  26. package/session.d.mts +63 -0
  27. package/session.mjs +2 -0
  28. package/session.mjs.map +1 -0
  29. package/utils/react-hooks.d.mts +24 -0
  30. package/utils/react-hooks.mjs +2 -0
  31. package/utils/react-hooks.mjs.map +1 -0
  32. package/README.md +0 -321
  33. package/__tests__/async-functions.ts +0 -43
  34. package/__tests__/async-generator-functions.ts +0 -137
  35. package/__tests__/convert-from-wire-format.ts +0 -65
  36. package/__tests__/convert-to-wire-format.ts +0 -66
  37. package/__tests__/describe.ts +0 -26
  38. package/__tests__/lib/adapter.ts +0 -47
  39. package/docs/extending.md +0 -19
  40. package/docs/protocol.md +0 -154
  41. package/examples/cli-chat/client.mjs +0 -21
  42. package/examples/cli-chat/package.json +0 -17
  43. package/examples/cli-chat/server.mjs +0 -48
  44. package/examples/cloudflare/README.md +0 -37
  45. package/examples/cloudflare/eslint.config.js +0 -19
  46. package/examples/cloudflare/index.html +0 -13
  47. package/examples/cloudflare/package.json +0 -29
  48. package/examples/cloudflare/public/vite.svg +0 -1
  49. package/examples/cloudflare/src/App.svelte +0 -450
  50. package/examples/cloudflare/src/api.ts +0 -33
  51. package/examples/cloudflare/src/main.ts +0 -4
  52. package/examples/cloudflare/tsconfig.app.json +0 -27
  53. package/examples/cloudflare/tsconfig.json +0 -14
  54. package/examples/cloudflare/tsconfig.node.json +0 -26
  55. package/examples/cloudflare/tsconfig.worker.json +0 -8
  56. package/examples/cloudflare/vite.config.ts +0 -8
  57. package/examples/cloudflare/worker/cloudflare.ts +0 -115
  58. package/examples/cloudflare/worker/index.ts +0 -17
  59. package/examples/cloudflare/worker/peer.ts +0 -47
  60. package/examples/cloudflare/worker-configuration.d.ts +0 -10922
  61. package/examples/cloudflare/wrangler.jsonc +0 -58
  62. package/examples/nodestreams/adapter.mjs +0 -36
  63. package/examples/nodestreams/child.mjs +0 -20
  64. package/examples/nodestreams/package.json +0 -14
  65. package/examples/nodestreams/parent.mjs +0 -20
  66. package/examples/reconnect/client.mjs +0 -22
  67. package/examples/reconnect/package.json +0 -15
  68. package/examples/reconnect/server.mjs +0 -30
  69. package/examples/tokens/client.mjs +0 -26
  70. package/examples/tokens/package.json +0 -20
  71. package/examples/tokens/server.mjs +0 -46
  72. package/make-package.js +0 -23
  73. package/src/adapters/reconnect.ts +0 -54
  74. package/src/adapters/resend.ts +0 -34
  75. package/src/adapters/socket.ts +0 -183
  76. package/src/adapters/websocket.ts +0 -157
  77. package/src/adapters/webworker.ts +0 -48
  78. package/src/codecs/cbor.ts +0 -239
  79. package/src/codecs/psionic.ts +0 -75
  80. package/src/psionic.ts +0 -876
  81. package/src/session.ts +0 -164
  82. package/src/utils/react-hooks.ts +0 -48
  83. package/tests +0 -8
  84. package/tsdown.config.ts +0 -19
@@ -1,137 +0,0 @@
1
- import assert from 'assert'
2
- import { createAsyncGeneratorFunction, createPeer, ErrorExpiredOrInvalid, ErrorGeneric } from '../src/psionic';
3
- import { createPair } from './lib/adapter';
4
-
5
- const description = {
6
- ok: async function *() {
7
- yield 'yield1';
8
- yield 'yield2';
9
- return 'ok';
10
- },
11
- fail: async function *() { throw new Error('fail') }
12
- };
13
-
14
- const left = createPeer({ description, sendErrorMessages: true });
15
- const right = createPeer({ description, receiveErrorMessages: true });
16
- await createPair(left, right);
17
-
18
- const asyncFailInvoker = createAsyncGeneratorFunction(left, ["fail"]);
19
- const asyncOkInvoker = createAsyncGeneratorFunction(left, ["ok"]);
20
-
21
- console.log('- Testing basic async generator function call');
22
- const okresult = asyncOkInvoker("hello");
23
- assert.deepStrictEqual(
24
- await okresult.next(),
25
- { value: 'yield1', done: false },
26
- 'The caller should receive the correct yielded value from the async generator'
27
- );
28
-
29
- await okresult.next();
30
-
31
- assert.deepStrictEqual(
32
- await okresult.next(),
33
- { value: 'ok', done: true },
34
- 'The caller should receive the correct return value from the async generator'
35
- );
36
-
37
- console.log('- Testing closing an async generator from the caller');
38
- const breakresult = asyncOkInvoker("hello");
39
- assert.deepStrictEqual(
40
- await breakresult.next(),
41
- { value: 'yield1', done: false },
42
- 'The caller should receive the correct yielded value from the async generator'
43
- );
44
-
45
- assert.deepStrictEqual(
46
- await breakresult.return('return'),
47
- { value: 'return', done: true },
48
- 'The caller should be able to close the async generator and receive the provided value'
49
- );
50
-
51
- assert.deepStrictEqual(
52
- await breakresult.next(),
53
- { value: undefined, done: true },
54
- 'After an async generator is closed, it should be completed and not yield any further values'
55
- );
56
-
57
- console.log('- Testing throwing an error into an async generator from the caller');
58
- const throwsresult = asyncOkInvoker("hello");
59
- assert.deepStrictEqual(
60
- await throwsresult.next(),
61
- { value: 'yield1', done: false },
62
- 'The caller should receive the correct yielded value from the async generator'
63
- );
64
-
65
- await throwsresult.throw('crash')
66
- .then(() => {
67
- assert.fail('The caller should not resolve successfully when an error is thrown into the async generator');
68
- })
69
- .catch(err => {
70
- assert.strictEqual(
71
- err.message,
72
- ErrorGeneric.error,
73
- 'The caller should receive a generic error message when an error is thrown into the async generator'
74
- );
75
- });
76
-
77
- assert.deepStrictEqual(
78
- await throwsresult.next(),
79
- { value: undefined, done: true },
80
- 'After an error is thrown into the async generator and caught, it should be completed'
81
- );
82
-
83
- console.log('- Testing async generator function that throws an error');
84
- const failresult = asyncFailInvoker("hello");
85
- await failresult.next()
86
- .then(() => {
87
- assert.fail('The caller should not resolve successfully when the async generator throws an error');
88
- })
89
- .catch(err => {
90
- assert.strictEqual(
91
- err.message,
92
- ErrorGeneric.error,
93
- 'The caller should receive a generic error message when an async generator throws an error'
94
- );
95
- });
96
-
97
- assert.deepStrictEqual(
98
- await failresult.next(),
99
- { value: undefined, done: true },
100
- 'After an async generator throws an error, it should be completed and not yield any further values'
101
- );
102
-
103
- console.log('- Testing concurrent async generator calls');
104
- {
105
- const g1 = asyncOkInvoker();
106
- const g2 = asyncOkInvoker();
107
-
108
- assert.deepStrictEqual(await g1.next(), { value: 'yield1', done: false }, 'concurrent g1 should receive the first yield');
109
- assert.deepStrictEqual(await g2.next(), { value: 'yield1', done: false }, 'concurrent g2 should receive the first yield');
110
- assert.deepStrictEqual(await g1.next(), { value: 'yield2', done: false }, 'concurrent g1 should receive the second yield');
111
- await g2.return(undefined);
112
- assert.deepStrictEqual(await g1.next(), { value: 'ok', done: true }, 'concurrent g1 should receive the return value and be completed');
113
- assert.deepStrictEqual(await g2.next(), { value: undefined, done: true }, 'concurrent g2 should be completed after being returned');
114
- }
115
-
116
- console.log('- Testing async generator expiration');
117
- {
118
- const g1 = asyncOkInvoker();
119
- assert.deepStrictEqual(await g1.next(),{ value: 'yield1', done: false },'The async generator should yield the first value correctly');
120
- right.session.clear();
121
- await g1.next()
122
- .then(() => { assert.fail('Expired generators should be cleaned up'); })
123
- .catch(err => {
124
- assert.strictEqual(
125
- err.message,
126
- ErrorExpiredOrInvalid.error,
127
- 'The caller should receive a generic error message when interacting with an expired async generator'
128
- );
129
- });
130
- assert.deepStrictEqual(
131
- await g1.next(),
132
- { value: undefined, done: true },
133
- 'After an async generator has expired, it should be completed and not yield any further values'
134
- );
135
- }
136
-
137
- console.log('- All async generator function tests passed successfully');
@@ -1,65 +0,0 @@
1
- import assert from 'assert'
2
- import { fromCodecDescription, createPeer, AsyncGenKey, AsyncFnKey, isAsyncGeneratorLike, Keyword } from '../src/psionic';
3
-
4
- const peer = createPeer();
5
-
6
- const allSimpleValues = () => ({
7
- 'hello': 'world',
8
- number: 9,
9
- nested: {
10
- arrayValue: [1,2,3],
11
- isThisATest: true
12
- }
13
- });
14
-
15
- console.log('- Testing converting a description from the wire format');
16
- assert.deepStrictEqual(
17
- fromCodecDescription(peer, allSimpleValues()),
18
- allSimpleValues(),
19
- 'Plain values should be unchanged'
20
- );
21
-
22
- console.log('- Testing that functions are not allowed in the wire format');
23
- assert.throws(
24
- () => fromCodecDescription(peer, { hello: () => 'world' } as any),
25
- 'Functions should throw an error, as they are not supported in the wire format'
26
- );
27
-
28
- console.log('- Testing that async function keywords are converted to actual async functions');
29
- assert.ok(
30
- fromCodecDescription(peer, { hello: { [Keyword]: AsyncFnKey } }).hello() instanceof Promise,
31
- 'Async functions keywords should be converted to actual async functions'
32
- );
33
-
34
- console.log('- Testing that async generator function keywords are converted to actual async generator functions');
35
- assert.ok(
36
- isAsyncGeneratorLike(fromCodecDescription(peer, { hello: { [Keyword]: AsyncGenKey } }).hello),
37
- 'Async generator functions keywords should be converted to actual async generator functions'
38
- );
39
-
40
- console.log('- Testing that Date instances are not allowed in the wire format');
41
- assert.throws(
42
- () => fromCodecDescription(peer, { hello: new Date() }),
43
- 'Date instances are not allowed in the wire format.'
44
- );
45
-
46
- console.log('- Testing that class instances are not allowed in the wire format');
47
- assert.throws(
48
- () => fromCodecDescription(peer, { hello: new (class X {})() }),
49
- 'Class instances are not allowed in the wire format.'
50
- );
51
-
52
- console.log('- Testing that objects without a prototype are not allowed in the wire format');
53
- assert.throws(
54
- () => fromCodecDescription(peer, { hello: Object.create(null) }),
55
- 'Objects without a prototype are not allowed in the wire format.'
56
- );
57
-
58
- console.log('- Testing that circular references are not allowed in the wire format');
59
- let nest: any = {}; nest.nest = nest;
60
- assert.throws(
61
- () => fromCodecDescription(peer, nest),
62
- 'Circular references are not allowed in the wire format.'
63
- );
64
-
65
- console.log('- All convert from wire format tests passed successfully');
@@ -1,66 +0,0 @@
1
- import assert from 'assert'
2
- import { AsyncFnKey, AsyncGenKey, Keyword, toCodecDescription } from '../src/psionic';
3
-
4
- const allSimpleValues = () => ({
5
- 'hello': 'world',
6
- number: 9,
7
- nested: {
8
- arrayValue: [1,2,3],
9
- isThisATest: true
10
- }
11
- });
12
-
13
- console.log('- Testing converting a description to the wire format');
14
- assert.deepStrictEqual(
15
- toCodecDescription(allSimpleValues()),
16
- allSimpleValues(),
17
- 'Plain values should be unchanged'
18
- );
19
-
20
- console.log('- Testing that functions are not allowed in the wire format');
21
- assert.deepStrictEqual(
22
- toCodecDescription({ hello: async () => 'world' }),
23
- { hello: { [Keyword]: AsyncFnKey } },
24
- 'Async functions should be replaced with transport keyword'
25
- );
26
-
27
- console.log('- Testing that async generator functions are not allowed in the wire format');
28
- assert.deepStrictEqual(
29
- toCodecDescription({ hello: async function* () { yield 'world' } }),
30
- { hello: { [Keyword]: AsyncGenKey } },
31
- 'Async generator functions should be replaced with transport keyword'
32
- );
33
-
34
- console.log('- Testing that functions are replaced with transport keywords even when nested in arrays');
35
- assert.deepStrictEqual(
36
- toCodecDescription([{ hello: async () => 'world' }]),
37
- [{ hello: { [Keyword]: AsyncFnKey } }],
38
- 'Function should be replaced with transport keyword even when nested in arrays'
39
- );
40
-
41
- console.log('- Testing that class instances are not allowed in descriptions');
42
- assert.throws(
43
- () => toCodecDescription({ hello: new Date() }),
44
- 'Date instances are not allowed in descriptions.'
45
- );
46
-
47
- console.log('- Testing that class instances are not allowed in descriptions');
48
- assert.throws(
49
- () => toCodecDescription({ hello: new (class X {})() }),
50
- 'Class instances are not allowed in descriptions.'
51
- );
52
-
53
- console.log('- Testing that objects without a prototype are not allowed in descriptions');
54
- assert.throws(
55
- () => toCodecDescription({ hello: Object.create(null) }),
56
- 'Objects without a prototype are not allowed in descriptions.'
57
- );
58
-
59
- console.log('- Testing that circular references are not allowed in descriptions');
60
- let nest: any = {}; nest.nest = nest;
61
- assert.throws(
62
- () => toCodecDescription(nest),
63
- 'Circular references are not allowed in descriptions.'
64
- );
65
-
66
- console.log('- All convert to wire format tests passed successfully');
@@ -1,26 +0,0 @@
1
- import assert from 'assert'
2
- import { createPeer } from '../src/psionic';
3
- import { createPair } from './lib/adapter';
4
-
5
- type Description ={ initial: boolean; hello?: string; third?: { value: string }; };
6
-
7
- const left = createPeer({ description: { initial: true, hello: 'there' } as Description });
8
- const right = createPeer({ });
9
-
10
- console.log('- Testing that peers receive the initial descriptions');
11
- await createPair(left, right);
12
-
13
- assert.deepStrictEqual(right.remote, { initial: true, hello: 'there' });
14
- assert.deepStrictEqual(left.remote, undefined);
15
-
16
- console.log('- Testing that peers can update their descriptions and the other peer receives the updated description');
17
- await left.describe({ initial: false, third: { value: 'key' } });
18
-
19
- assert.deepStrictEqual(right.remote, { initial: false, third: { value: 'key' } });
20
-
21
- console.log('- Testing that peers can merge updates to their descriptions and the other peer receives the merged description');
22
- await left.describe(d => ({ ...d, third: { value: 'merged' } }));
23
-
24
- assert.deepStrictEqual(right.remote, { initial: false, third: { value: 'merged' } });
25
-
26
- console.log('- All describe tests passed successfully');
@@ -1,47 +0,0 @@
1
- import { type Peer, type Frame, type Connection } from '../../src/psionic';
2
- import { psionicCodec } from '../../src/codecs/psionic';
3
- const codec = psionicCodec();
4
-
5
- export async function createPair(leftPeer: Peer, rightPeer: Peer) {
6
- let leftMessages: Frame[] = [];
7
- let rightMessages: Frame[] = [];
8
- let right: Connection | undefined;
9
- let left: Connection | undefined;
10
- left = ({
11
- close: () => {},
12
- send: (message: Frame) => {
13
- console.log('L>', codec.messageToWire(message));
14
- leftMessages.push(message);
15
- queueMicrotask(() => {
16
- if (!rightPeer.connection) {
17
- console.warn('Right peer is not connected yet, cannot deliver message');
18
- return;
19
- }
20
- rightPeer.handleMessage(codec.messageFromWire(codec.messageToWire(message)));
21
- });
22
- }
23
- });
24
- right = ({
25
- close: () => {},
26
- send: (message: Frame) => {
27
- console.log('R>', codec.messageToWire(message));
28
- rightMessages.push(message);
29
- queueMicrotask(() => {
30
- if (!leftPeer.connection) {
31
- console.warn('Left peer is not connected yet, cannot deliver message');
32
- return;
33
- }
34
- leftPeer.handleMessage(codec.messageFromWire(codec.messageToWire(message)));
35
- });
36
- }
37
- });
38
- leftPeer.on('error', () => {});
39
- rightPeer.on('error', () => {});
40
- let pl = leftPeer.connect(async p => left, false);
41
- let pr = rightPeer.connect(async p => right, false);
42
-
43
- console.log('- Waiting for both peers to connect');
44
- await Promise.all([pl, pr]);
45
- console.log('- Both peers connected successfully');
46
- return { left, right, leftMessages, rightMessages };
47
- }
package/docs/extending.md DELETED
@@ -1,19 +0,0 @@
1
- # Extending Psionic
2
-
3
- You can extend Psionic with new transport adapters, communication codecs and policies. The frames themselves are fixed by the protocol, but the way they are encoded and transmitted can be customized by implementing new codecs and transports.
4
-
5
- ## Codecs
6
-
7
- A codec defines how frames are encoded into bytes for transmission, and decoded back into frames on the receiving end. There are built-in codecs for space-separated JSON messages and CBOR. The objects have a couple of symbols to indicate special values that aren't easily represented in JSON, such as `AsyncFnKey` and `AsyncGenKey`.
8
-
9
- The `codec` interface is two functions, `messageFromWire` and `messageToWire`, which convert between frames and byte arrays or strings. There is also a `type` parameter which can be `text` or `binary`. You can create a new codec by implementing these functions to encode frames in a different format, such as MessagePack, Protobuf, or a custom binary format.
10
-
11
- ## Transport Adapters
12
-
13
- A transport adapter defines how encoded frames are transmitted between peers. There are built-in transports for Node.js Sockets, Web Sockets and Web Workers. You can create a new transport by implementing the `Adapter` interface.
14
-
15
- Look at the `nodestreams` example for a simple adapter that uses Node.js child process stdio streams as the transport layer.
16
-
17
- ## Operation Tracking and Policies
18
-
19
- The `Session` keeps track of all in-flight operations (promises, generators, incoming calls) for the peer connection. It provides a way to correlate responses to their original requests, enforce timeouts, and clean up resources on disconnect. You can create a custom operation tracker by implementing the `Session` interface, or use the provided `createSession` function which provides a reasonable default implementation with configurable timeouts.
package/docs/protocol.md DELETED
@@ -1,154 +0,0 @@
1
- # Psionic Protocol
2
-
3
- The psionic protocol is kept intentionally minimal. These examples are shown using the psionic wire codec, designed to be easy to debug and interact with manually and in constrained environments, but the same protocol can be implemented over any transport layer and with any serialization format.
4
-
5
- Each `frame` is a tuple of `[type, id, ...args]`
6
-
7
- 1. `type` is a single character string indicating the frame type
8
-
9
- 2. `id` is a string identifier that is written back in responses to the caller so they can correlate responses to their requests.
10
-
11
- 3. `args` is any additional data needed for the frame, which varies based on the frame type.
12
-
13
- ## Frame types
14
-
15
- ### *`D`* - Describe
16
-
17
- **Example**
18
- ```
19
- D "1" {"name":"Alice","greet":{"@@psion":"f"},"worker":{"@@psion":"g"}} true
20
- ```
21
-
22
- Send a new set of capabilities and state to the remote peer. The sender provides a description object, which is a structure that contains any combination of nested objects, arrays, primitive values, and functions. The receiver gets a live-updating view of this description as it changes over time, and can call functions within it as if they were local.
23
-
24
- #### Frame arguments:
25
-
26
- 1. `description`: A nested object containing any combination of primitive values, objects, arrays, and functions. `{"@@psion":"f"}` indicates a callable function, and `{"@@psion":"g"}` for async generators.
27
-
28
- 2. `swap` (optional): A boolean flag indicating whether the description should replace the existing remote description (`true`), or be merged with it (`false` or omitted). If `swap` is `true`, the provided description completely replaces the existing remote description. If `swap` is `false` or omitted, the provided description is merged with the existing remote description, allowing for incremental updates.
29
-
30
- ### *`C`* - Call
31
-
32
- **Example**
33
- ```
34
- C "2" ["greet"] ["Hello, %s!"]
35
- ```
36
-
37
- Invoke a function on the remote peer. The caller provides the path to the function within the remote description, and an array of arguments to call it with. The callee receives the call, executes the function, and sends back a response frame with the result.
38
-
39
- If the function is a generator, the callee instead sends an iterator ID, which can be iterated over the generator with `.` (next), `<` (return), and `>` (throw) frames.
40
-
41
- #### Frame arguments:
42
-
43
- 1. `name`: An array of strings representing the path to the function within the remote description. For example, `["user", "load"]` would call `peer.remote.user.load()`.
44
-
45
- 2. `args`: An array of arguments to call the function with.
46
-
47
- ### *`K`* - OK
48
-
49
- **Example**
50
- ```
51
- K "2" "Hello, Alice!"
52
- ```
53
-
54
- Send a successful response back to the caller after any frame that expects a response (e.g. `D`, `C`, `.`, `>`) The `id` field matches the `id` of the original call frame, so the caller can correlate the response to their request.
55
-
56
- For iterators (`.`, `<`, `>`), responses are an array where the first item is a `yielded` value, and the second is a `0` or `1` indicating if the generator is done. Continuing to call `next` on a completed generator will return an error.
57
-
58
- #### Frame arguments:
59
-
60
- 1. `result`: The result of the call, which can be any value.
61
-
62
- ### *`E`* - Error
63
-
64
- **Example**
65
- ```
66
- E "2" 0 "Cannot greet user, server is shy."
67
- ```
68
-
69
- Send an error response back to the caller after any frame that expects a response (e.g. `D`, `C`, `.`, `>`) The `id` field matches the `id` of the original call frame, so the caller can correlate the response to their request.
70
-
71
- #### Frame arguments:
72
-
73
- 1. `code`: A numeric error code.
74
-
75
- 2. `error` (optional): A string describing the error.
76
-
77
- ### *`.`* - Iterator Next
78
-
79
- **Example**
80
- ```
81
- . "3" "iterator-1" "Next value"
82
- ```
83
-
84
- Advance a remote iterator to its next yield point. The `operationId` field matches the return of the original call frame that created the iterator. The callee responds with either an `OK` frame containing the yielded value, or an `Error` frame if the iterator is completed or throws.
85
-
86
- #### Frame arguments:
87
-
88
- 1. `operationId`: The ID of the iterator to advance, as returned by the original call frame.
89
-
90
- 2. `value`: An optional value to send into the generator, for `yield` expressions.
91
-
92
- ### `<` - Iterator Return
93
-
94
- **Example**
95
- ```
96
- < "3" "iterator-1" "Final value"
97
- ```
98
-
99
- Stop the iteration of a remote iterator, completing it. The `operationId` field matches the return of the original call frame that created the iterator. The callee responds with an `OK` frame confirming completion, or an `Error` frame if the iterator is already completed or throws.
100
-
101
- #### Frame arguments:
102
-
103
- 1. `operationId`: The ID of the iterator to close, as returned by the original `Call` frame.
104
-
105
- 2. `value`: An optional return value to send into the generator.
106
-
107
- ### `>` - Iterator Throw
108
-
109
- **Example**
110
- ```
111
- > "3" "iterator-1" 0 "Something went wrong"
112
- ```
113
-
114
- Used to throw an error into a remote iterator. The `operationId` field matches the return of the original call frame that created the iterator. The callee responds with either an `OK` frame containing the value returned by the generator, or an `Error` frame if the iterator is already completed or throws.
115
-
116
- #### Frame arguments:
117
-
118
- 1. `operationId`: The ID of the iterator to advance, as returned by the original `Call` frame.
119
-
120
- 2. `code`: A numeric error code.
121
-
122
- 3. `error` (optional): A string describing the error.
123
-
124
- # Errors
125
-
126
- There are some standard errors defined by the protocol, but applications are free to define their own error codes and messages as well.
127
-
128
- ## *`0`* - Remote error
129
-
130
- The generic remote error code indicates that an error occurred on the remote peer while processing a request. The error message may contain additional details about the error, but this is not guaranteed.
131
-
132
- ## *`1`* - No remote assigned
133
-
134
- This error indicates that a call was attempted without an active remote peer connection. This can happen if the peer has not yet connected to a remote, or if the connection was lost.
135
-
136
- ## *`2`* - Disconnected
137
-
138
- This error indicates that the connection to the remote peer was lost while a request was in-flight. The request may or may not have been processed by the remote peer.
139
-
140
- ## *`3`* - Protocol violation
141
-
142
- This error indicates that a message was received that does not conform to the expected protocol format. This can happen if someone is sending data leading to corrupted frames or missing arguments.
143
-
144
- ## *`4`* - Function not found
145
-
146
- This error indicates that a call was made to a function that does not exist on the remote peer's description. This can happen if the caller has an outdated view of the remote description, or if the caller is trying to call a function that was never described.
147
-
148
- ## *`5`* - Expired or invalid
149
-
150
- This error indicates that a call was made with an ID that is no longer valid. This can happen if the caller is trying to respond to a call that has already been responded to, or if the caller is trying to interact with an iterator that has already completed.
151
-
152
- ## *`6`* - Rejected
153
-
154
- This error indicates that a call was rejected by the remote peer. This can happen if the remote peer is overloaded, or if the remote peer has some application-level logic for rejecting certain calls.
@@ -1,21 +0,0 @@
1
- import { createPeer } from "psionic";
2
-
3
- // create a peer, with the description we want to send when we connect.
4
- // could be anything, in this case, just the model we want the server to use.
5
- const peer = createPeer({ description: { model: process.argv[3] || 'gpt-5.2' } });
6
-
7
- // connect to the local socket
8
- import { createConnection } from "net";
9
- import { createNodeSocketAdapter } from "psionic/adapters/socket";
10
- await peer.connect(createNodeSocketAdapter(createConnection({ port: 1234 })));
11
-
12
- // pass the argument from the command line to the server's prompt function
13
- for await (const chunk of peer.remote.prompt(process.argv[2])) {
14
- // and stream the response back to the console as it comes in!
15
- if (chunk.type === 'response.output_text.delta')
16
- process.stdout.write(String(chunk.delta));
17
- }
18
-
19
- // close the connection so that the process exits
20
- peer.close();
21
- console.log('');
@@ -1,17 +0,0 @@
1
- {
2
- "name": "cli-chat",
3
- "private": true,
4
- "version": "1.0.0",
5
- "description": "",
6
- "license": "ISC",
7
- "author": "",
8
- "type": "module",
9
- "main": "index.js",
10
- "scripts": {
11
- "test": "echo \"Error: no test specified\" && exit 1"
12
- },
13
- "dependencies": {
14
- "openai": "^6.22.0",
15
- "psionic": "file:../.."
16
- }
17
- }
@@ -1,48 +0,0 @@
1
- import { createPeer } from "psionic";
2
- import OpenAI from "openai";
3
-
4
- // listen for incoming socket connections and create a new peer for each one
5
- import { createServer } from "net";
6
- import { createNodeSocketAdapter } from "psionic/adapters/socket";
7
- createServer(socket => handlePeer(createNodeSocketAdapter(socket))).listen(1234);
8
-
9
- // global conversation_id for demo purposes.
10
- let conversation_id = undefined;
11
-
12
- async function handlePeer(adapter) {
13
- const peer = createPeer();
14
- await peer.connect(adapter);
15
-
16
- const openAI = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
17
- // send a list of functions and properties to the client.
18
- // they can access this under peer.remote from their end, and we can update it at any time.
19
- await peer.describe(desc => ({ ...desc, prompt }));
20
-
21
- // this is a function that can be called by the client.
22
- // it returns an async generator, which allows us to stream data back to the client in chunks.
23
- async function* prompt(input) {
24
- try {
25
- const data = await openAI.responses.create({
26
- // peer.remote is a live-updating view of the client's described state.
27
- model: peer.remote?.model || 'gpt-5.2',
28
- store: true,
29
- stream: true,
30
- previous_response_id: conversation_id,
31
- tools: [{ type: "web_search" }],
32
- instructions: `Send really terse responses.`,
33
- input: String(input)
34
- });
35
- for await (const part of data) {
36
- console.log(part.type, part.sequence_number);
37
- if (part.type === 'response.completed')
38
- conversation_id = part.response.id;
39
- // yield one chunk to the client at a time
40
- // this waits until they ask for the next one before continuing.
41
- yield part;
42
- }
43
- } finally {
44
- // this will run if the peer disconnects, times out, or if the function completes!
45
- console.log('prompt ended!');
46
- }
47
- }
48
- }
@@ -1,37 +0,0 @@
1
- # Cloudflare + Psionic Example
2
-
3
- This example shows a simple Svelte chat application that runs in a Cloudflare Durable Object.
4
-
5
- To run it, you'll need to fill in an OpenAI key in the `.env` file, like:
6
-
7
- ```
8
- OPENAI_API_KEY=sk-...
9
- ```
10
-
11
- Then you can run the development server with:
12
-
13
- ```
14
- npm install
15
- npm run dev
16
- ```
17
-
18
- To publish it to your own Cloudflare account run:
19
-
20
- ```
21
- npx wrangler secret put OPENAI_API_KEY
22
- npm run deploy
23
- ```
24
-
25
- ## Structure
26
-
27
- ### Frontend
28
-
29
- `src/api.ts` connects to the Cloudflare worker and sets up the Psionic peer.
30
-
31
- `src/App.svelte` is the main Svelte component, which uses the peer to send messages and receive responses.
32
-
33
- ### Backend
34
-
35
- `worker/cloudflare.ts` configures the Cloudflare Durable Object and sets up the Psionic peer, if the peer disconnects for 15 seconds the session is removed from the DO.
36
-
37
- `worker/peer.ts` contains the logic for handling incoming messages, generating responses using the OpenAI API, and sending them back to the client.
@@ -1,19 +0,0 @@
1
- import js from '@eslint/js'
2
- import globals from 'globals'
3
- import tseslint from 'typescript-eslint'
4
- import { defineConfig, globalIgnores } from 'eslint/config'
5
-
6
- export default defineConfig([
7
- globalIgnores(['dist']),
8
- {
9
- files: ['**/*.{ts,tsx}'],
10
- extends: [
11
- js.configs.recommended,
12
- tseslint.configs.recommended
13
- ],
14
- languageOptions: {
15
- ecmaVersion: 2020,
16
- globals: globals.browser,
17
- },
18
- },
19
- ])