@matatbread/matbot-session-data 0.0.0-stage → 0.5.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/LICENSE +201 -0
- package/README.md +37 -2
- package/package.json +42 -3
- package/src/entries.ts +87 -0
- package/src/index.ts +167 -0
- package/src/shape.ts +66 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 Mat Woolf
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,38 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @matatbread/matbot-session-data
|
|
2
2
|
|
|
3
|
-
This
|
|
3
|
+
This is a [matbot](https://github.com/MatAtBread/matbot) plugin.
|
|
4
|
+
|
|
5
|
+
Keep intermediate results in a conversation and read them back by id. `session_data` is a registered tool
|
|
6
|
+
(Node and browser):
|
|
7
|
+
|
|
8
|
+
- `write { description, data }` → `{ id, description, shape, bytes, createdAt }`: keeps `data` (any JSON, at
|
|
9
|
+
most 65536 bytes) and reports its TypeScript type as `shape`.
|
|
10
|
+
- `read { id }` → the data, as written.
|
|
11
|
+
- `list` → every entry held, without its data.
|
|
12
|
+
- `drop { id }` → `{ dropped }`.
|
|
13
|
+
|
|
14
|
+
Its use is passing a tool's output to a later step without the model reading it. From a `tool_function` body:
|
|
15
|
+
|
|
16
|
+
```ts
|
|
17
|
+
// "get the count of items per day for the last week, and keep it to one side"
|
|
18
|
+
{ const rows = await tool.sql({ query: 'select day, count(*) as size from data_table' });
|
|
19
|
+
return await tool.session_data({ action: 'write', description: 'items per day, last week', data: rows }); }
|
|
20
|
+
|
|
21
|
+
// later: "draw a chart of those daily counts"
|
|
22
|
+
{ const rows = await tool.session_data({ action: 'read', id: 'k3f9a2pq' });
|
|
23
|
+
return await tool.draw_chart({ data: rows }); }
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
The model reads back the entry's id, description and type, never its rows. In code checked on the
|
|
27
|
+
conversation's behalf (an `execute` body, a session function), a read by a literal id is typed by what the
|
|
28
|
+
entry holds, so `rows` passes to a typed tool as it is; a read by an id known only at run time is `unknown`.
|
|
29
|
+
A global function can call `session_data` too: it cannot know what any conversation holds, so its reads are
|
|
30
|
+
`unknown` and narrowed, and a read of an id the conversation running it does not hold is an error.
|
|
31
|
+
|
|
32
|
+
The type is inferred from the value when it is read, and reaches the type-checker through `SessionTypes`
|
|
33
|
+
(`sessionType` on the tool). The description is the same in every conversation, so writing an entry never
|
|
34
|
+
changes a tool definition (which would discard a provider's prompt cache); `list` shows what is held.
|
|
35
|
+
|
|
36
|
+
Entries are stored as markers in the conversation: private to it, shared when it is shared, carried by fork
|
|
37
|
+
and compaction, gone if it is cut back past where they were written, and never sent to a model. An entry
|
|
38
|
+
never changes; write a new one instead.
|
package/package.json
CHANGED
|
@@ -1,6 +1,45 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@matatbread/matbot-session-data",
|
|
3
|
-
"
|
|
4
|
-
|
|
5
|
-
|
|
3
|
+
"matbotRuntime": [
|
|
4
|
+
"node",
|
|
5
|
+
"browser"
|
|
6
|
+
],
|
|
7
|
+
"version": "0.5.0",
|
|
8
|
+
"engines": {
|
|
9
|
+
"node": ">=24.0.0"
|
|
10
|
+
},
|
|
11
|
+
"files": [
|
|
12
|
+
"src"
|
|
13
|
+
],
|
|
14
|
+
"description": "Keep intermediate results in a conversation and read them back by id: private to the session, and shared when it is shared.",
|
|
15
|
+
"keywords": [
|
|
16
|
+
"matbot",
|
|
17
|
+
"matbot-plugin",
|
|
18
|
+
"llm",
|
|
19
|
+
"ai",
|
|
20
|
+
"agent"
|
|
21
|
+
],
|
|
22
|
+
"license": "Apache-2.0",
|
|
23
|
+
"type": "module",
|
|
24
|
+
"exports": {
|
|
25
|
+
".": "./src/index.ts"
|
|
26
|
+
},
|
|
27
|
+
"repository": {
|
|
28
|
+
"type": "git",
|
|
29
|
+
"url": "git+https://github.com/MatAtBread/matbot.git",
|
|
30
|
+
"directory": "plugins/session-data"
|
|
31
|
+
},
|
|
32
|
+
"publishConfig": {
|
|
33
|
+
"access": "public"
|
|
34
|
+
},
|
|
35
|
+
"peerDependencies": {
|
|
36
|
+
"@matatbread/matbot-plugin-api": "^0.5.0"
|
|
37
|
+
},
|
|
38
|
+
"devDependencies": {
|
|
39
|
+
"typescript": "^6.0.3",
|
|
40
|
+
"@matatbread/matbot-plugin-api": "^0.5.0"
|
|
41
|
+
},
|
|
42
|
+
"scripts": {
|
|
43
|
+
"typecheck": "tsc --noEmit"
|
|
44
|
+
}
|
|
6
45
|
}
|
package/src/entries.ts
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import type { Session } from '@matatbread/matbot-plugin-api';
|
|
2
|
+
import { shapeOf } from './shape.js';
|
|
3
|
+
|
|
4
|
+
export const SESSION_DATA_CREATOR = '@matatbread/matbot-session-data';
|
|
5
|
+
|
|
6
|
+
/** At most this many bytes of JSON in one entry. Every entry is part of the session document, which is
|
|
7
|
+
* written whole at the start and end of each turn. */
|
|
8
|
+
export const MAX_ENTRY_BYTES = 65536;
|
|
9
|
+
|
|
10
|
+
export interface SessionDataInfo {
|
|
11
|
+
id: string;
|
|
12
|
+
description: string;
|
|
13
|
+
/** The entry's TypeScript type, inferred from its value when it was written. */
|
|
14
|
+
shape: string;
|
|
15
|
+
/** The size of its JSON, in UTF-8 bytes. */
|
|
16
|
+
bytes: number;
|
|
17
|
+
createdAt: string;
|
|
18
|
+
}
|
|
19
|
+
export interface SessionDataEntry extends SessionDataInfo { data: unknown }
|
|
20
|
+
|
|
21
|
+
/** An entry is written once and never changed; `drop` is a later marker saying it is gone. */
|
|
22
|
+
export type SessionDataMarker = ({ op: 'write' } & SessionDataEntry) | { op: 'drop'; id: string };
|
|
23
|
+
|
|
24
|
+
declare module '@matatbread/matbot-plugin-api' {
|
|
25
|
+
interface MarkerData { '@matatbread/matbot-session-data': SessionDataMarker }
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface Held {
|
|
29
|
+
/** In the order they were written. */
|
|
30
|
+
entries: Map<string, SessionDataEntry>;
|
|
31
|
+
dropped: Set<string>;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// Persisted data, so checked rather than trusted: a hand-edited or foreign marker is skipped.
|
|
35
|
+
function parse(data: unknown): SessionDataMarker | undefined {
|
|
36
|
+
if (typeof data !== 'object' || data === null) return undefined;
|
|
37
|
+
const d = data as Partial<Record<keyof SessionDataEntry | 'op', unknown>>;
|
|
38
|
+
if (typeof d.id !== 'string') return undefined;
|
|
39
|
+
if (d.op === 'drop') return { op: 'drop', id: d.id };
|
|
40
|
+
if (d.op !== 'write' || !('data' in d) || typeof d.description !== 'string'
|
|
41
|
+
|| typeof d.bytes !== 'number' || typeof d.createdAt !== 'string') return undefined;
|
|
42
|
+
// The shape is derived again rather than read: it is spliced into a type-check as source, and a stored
|
|
43
|
+
// string is whatever last edited the session file — `any` would pass every read, and worse could rewrite
|
|
44
|
+
// the declarations around it. The value is the entry; its type follows from it.
|
|
45
|
+
return { op: 'write', id: d.id, description: d.description, shape: shapeOf(d.data), bytes: d.bytes, createdAt: d.createdAt, data: d.data };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function apply(held: Held, m: SessionDataMarker): void {
|
|
49
|
+
if (m.op === 'drop') { held.entries.delete(m.id); held.dropped.add(m.id); return; }
|
|
50
|
+
const { op: _op, ...entry } = m;
|
|
51
|
+
held.entries.set(m.id, entry);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* What one call has written that its session does not show yet. A tool's markers reach the session when
|
|
56
|
+
* the call that yielded them ends, so a body that writes and then reads (itself, or through another tool
|
|
57
|
+
* it calls) would otherwise find nothing. Keyed on the session OBJECT a call was handed: every call made
|
|
58
|
+
* within one call is handed that same object, and when it ends the runner moves on to a new one holding
|
|
59
|
+
* the markers, so nothing ever has to be cleared and nothing outlives the window it covers. A turn aborted
|
|
60
|
+
* before its markers were kept takes its session object, and so these, with it.
|
|
61
|
+
*/
|
|
62
|
+
const pending = new WeakMap<Session, SessionDataMarker[]>();
|
|
63
|
+
|
|
64
|
+
export function remember(session: Session, m: SessionDataMarker): void {
|
|
65
|
+
const list = pending.get(session);
|
|
66
|
+
if (list === undefined) pending.set(session, [m]);
|
|
67
|
+
else list.push(m);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** What `session` holds: its markers in order, then whatever calls on this very session object wrote. */
|
|
71
|
+
export function held(session: Session): Held {
|
|
72
|
+
const out: Held = { entries: new Map(), dropped: new Set() };
|
|
73
|
+
for (const msg of session.messages) {
|
|
74
|
+
if (msg.role !== 'marker') continue;
|
|
75
|
+
for (const c of msg.content) {
|
|
76
|
+
if (c.type !== 'marker' || c.creator !== SESSION_DATA_CREATOR) continue;
|
|
77
|
+
const m = parse(c.data);
|
|
78
|
+
if (m !== undefined) apply(out, m);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
for (const m of pending.get(session) ?? []) apply(out, m);
|
|
82
|
+
return out;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function info({ data: _data, ...rest }: SessionDataEntry): SessionDataInfo {
|
|
86
|
+
return rest;
|
|
87
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import type { MatbotPluginSpec, Session, SessionTypes, Tool, ToolContext, ToolContract, ToolEvent } from '@matatbread/matbot-plugin-api';
|
|
2
|
+
import { PLUGIN_API_VERSION } from '@matatbread/matbot-plugin-api';
|
|
3
|
+
import { held, info, MAX_ENTRY_BYTES, remember, SESSION_DATA_CREATOR, type SessionDataEntry, type SessionDataInfo } from './entries.js';
|
|
4
|
+
import { shapeOf } from './shape.js';
|
|
5
|
+
|
|
6
|
+
export { MAX_ENTRY_BYTES, SESSION_DATA_CREATOR, type SessionDataEntry, type SessionDataInfo, type SessionDataMarker } from './entries.js';
|
|
7
|
+
export { shapeOf } from './shape.js';
|
|
8
|
+
|
|
9
|
+
export const TOOL_NAME = 'session_data';
|
|
10
|
+
|
|
11
|
+
/** What each entry of the session being checked holds, by id: this tool's key of `SessionTypes`, which only
|
|
12
|
+
* a check made on a session's behalf fills (from {@link sessionType}). Empty for a global function, which
|
|
13
|
+
* cannot know what any conversation holds. */
|
|
14
|
+
export type SessionDataEntries = SessionTypes extends { readonly session_data: infer E } ? E : Record<never, never>;
|
|
15
|
+
|
|
16
|
+
/** What `read` of `K` returns: the entry's type when the check knows it, else `unknown`. */
|
|
17
|
+
export type SessionDataRead<K extends string> = K extends keyof SessionDataEntries ? SessionDataEntries[K] : unknown;
|
|
18
|
+
|
|
19
|
+
declare module '@matatbread/matbot-plugin-api' {
|
|
20
|
+
interface ToolContracts {
|
|
21
|
+
session_data:
|
|
22
|
+
| ToolContract<SessionDataInfo, { action: 'write'; description: string; data: unknown }>
|
|
23
|
+
| ToolContract<unknown, { action: 'read'; id: string }, <K extends string>(params: { action: 'read'; id: K }) => Promise<SessionDataRead<K>>>
|
|
24
|
+
| ToolContract<SessionDataInfo[], { action: 'list' }>
|
|
25
|
+
| ToolContract<{ dropped: string }, { action: 'drop'; id: string }>;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const ID_ALPHABET = 'abcdefghijkmnpqrstuvwxyz23456789'; // no l/1/o/0: an id is copied by a model
|
|
30
|
+
const ID_LENGTH = 8;
|
|
31
|
+
|
|
32
|
+
function newId(taken: (id: string) => boolean): string {
|
|
33
|
+
for (;;) {
|
|
34
|
+
const bytes = crypto.getRandomValues(new Uint8Array(ID_LENGTH));
|
|
35
|
+
const id = [...bytes].map(b => ID_ALPHABET[b % ID_ALPHABET.length]).join('');
|
|
36
|
+
if (!taken(id)) return id;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const ALLOWED: Record<string, readonly string[]> = {
|
|
41
|
+
write: ['action', 'description', 'data'],
|
|
42
|
+
read: ['action', 'id'],
|
|
43
|
+
list: ['action'],
|
|
44
|
+
drop: ['action', 'id'],
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
type Outcome = ToolEvent<unknown>;
|
|
48
|
+
const refuse = (message: string): Outcome => ({ type: 'error', message, failure: 'invalid' });
|
|
49
|
+
|
|
50
|
+
// A turn tool is not wrapped by the registry's executor, so no `validate` hook sees its input: it checks
|
|
51
|
+
// its own, and as strictly — an unknown property is a misspelt one.
|
|
52
|
+
function check(params: unknown): { action: string; p: Record<string, unknown> } | Outcome {
|
|
53
|
+
if (typeof params !== 'object' || params === null || Array.isArray(params)) return refuse('session_data takes an object: { "action": "write" | "read" | "list" | "drop", … }.');
|
|
54
|
+
const p = params as Record<string, unknown>;
|
|
55
|
+
const action = p['action'];
|
|
56
|
+
if (typeof action !== 'string' || !(action in ALLOWED)) return refuse(`"action" is one of write, read, list or drop${action === undefined ? '' : `, not ${JSON.stringify(action)}`}.`);
|
|
57
|
+
const stray = Object.keys(p).filter(k => !ALLOWED[action]!.includes(k));
|
|
58
|
+
if (stray.length > 0) return refuse(`"${action}" takes ${ALLOWED[action]!.map(k => `"${k}"`).join(', ')}; not ${stray.map(k => `"${k}"`).join(', ')}.`);
|
|
59
|
+
return { action, p };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
async function* execute(params: unknown, ctx: ToolContext): AsyncIterable<Outcome> {
|
|
63
|
+
const checked = check(params);
|
|
64
|
+
if ('type' in checked) { yield checked; return; }
|
|
65
|
+
const { action, p } = checked;
|
|
66
|
+
const now = held(ctx.session);
|
|
67
|
+
|
|
68
|
+
switch (action) {
|
|
69
|
+
case 'write': {
|
|
70
|
+
// A `#` session is a door, not a conversation: nothing written there is kept, so an id would be a lie.
|
|
71
|
+
if (ctx.session.id.startsWith('#')) { yield refuse('This call is not part of a conversation, so there is nowhere to keep data.'); return; }
|
|
72
|
+
const description = p['description'];
|
|
73
|
+
if (typeof description !== 'string' || description.trim() === '') { yield refuse('"write" needs a "description": what the data is, so it can be found again.'); return; }
|
|
74
|
+
if (!('data' in p)) { yield refuse('"write" needs "data": the value to keep.'); return; }
|
|
75
|
+
let json: string | undefined;
|
|
76
|
+
try { json = JSON.stringify(p['data']); }
|
|
77
|
+
catch (e) { yield refuse(`The data cannot be kept as JSON: ${e instanceof Error ? e.message : String(e)}.`); return; }
|
|
78
|
+
if (json === undefined) { yield refuse('The data cannot be kept as JSON: it has no JSON form (undefined, or a function).'); return; }
|
|
79
|
+
const bytes = new TextEncoder().encode(json).length;
|
|
80
|
+
if (bytes > MAX_ENTRY_BYTES) {
|
|
81
|
+
yield refuse(`This data is ${bytes} bytes and session_data holds at most ${MAX_ENTRY_BYTES}. Store the intermediate results using tools that accept data of ${bytes} bytes.`);
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
// What is kept is what JSON keeps (an `undefined` property gone, `NaN` as null), and a read now
|
|
85
|
+
// returns exactly what a read after a restart will.
|
|
86
|
+
const data: unknown = JSON.parse(json);
|
|
87
|
+
const entry: SessionDataEntry = {
|
|
88
|
+
id: newId(id => now.entries.has(id) || now.dropped.has(id)),
|
|
89
|
+
description: description.trim(), shape: shapeOf(data), bytes, createdAt: new Date().toISOString(), data,
|
|
90
|
+
};
|
|
91
|
+
remember(ctx.session, { op: 'write', ...entry });
|
|
92
|
+
yield { type: 'marker', creator: SESSION_DATA_CREATOR, data: { op: 'write', ...entry } };
|
|
93
|
+
yield { type: 'result', value: info(entry) };
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
case 'read': {
|
|
97
|
+
const id = p['id'];
|
|
98
|
+
if (typeof id !== 'string') { yield refuse('"read" needs the "id" a write returned.'); return; }
|
|
99
|
+
const entry = now.entries.get(id);
|
|
100
|
+
if (entry !== undefined) { yield { type: 'result', value: entry.data }; return; }
|
|
101
|
+
yield refuse(now.dropped.has(id)
|
|
102
|
+
? `Entry "${id}" was dropped.`
|
|
103
|
+
: `This conversation holds no entry "${id}". ${now.entries.size > 0 ? `It holds: ${[...now.entries.keys()].join(', ')}.` : 'It holds none.'}`);
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
case 'list': {
|
|
107
|
+
yield { type: 'result', value: [...now.entries.values()].map(info) };
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
case 'drop': {
|
|
111
|
+
const id = p['id'];
|
|
112
|
+
if (typeof id !== 'string') { yield refuse('"drop" needs the "id" of an entry.'); return; }
|
|
113
|
+
if (!now.entries.has(id)) { yield refuse(now.dropped.has(id) ? `Entry "${id}" was dropped already.` : `This conversation holds no entry "${id}".`); return; }
|
|
114
|
+
remember(ctx.session, { op: 'drop', id });
|
|
115
|
+
yield { type: 'marker', creator: SESSION_DATA_CREATOR, data: { op: 'drop', id } };
|
|
116
|
+
yield { type: 'result', value: { dropped: id } };
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
default:
|
|
120
|
+
yield refuse(`Unknown action "${action}".`);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** This session's entries as a type, for one check: each id with the type inferred from its value when it
|
|
125
|
+
* was written. Exact, because an entry never changes. One lookup in a map rather than an overload per
|
|
126
|
+
* entry, so a check costs the same and a refusal reads the same however many a session holds. */
|
|
127
|
+
export function sessionType(session: Session): string | undefined {
|
|
128
|
+
const entries = [...held(session).entries.values()];
|
|
129
|
+
if (entries.length === 0) return undefined;
|
|
130
|
+
return `{ ${entries.map(e => `${JSON.stringify(e.id)}: ${e.shape};`).join(' ')} }`;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const DESCRIPTION = `Keep a value in this conversation and read it back later by its id: an intermediate result (a query's rows, an aggregate) that a later step needs, without repeating it into the conversation. An entry belongs to the conversation: it is shared when the conversation is shared, goes with it when forked, and is gone if the conversation is cut back past where it was written. An entry never changes; write a new one instead. At most ${MAX_ENTRY_BYTES} bytes of JSON each.
|
|
134
|
+
|
|
135
|
+
Actions:
|
|
136
|
+
- write { description, data } → { id, description, shape, bytes, createdAt }. \`description\` says what the data is, so it can be found again; \`shape\` is its TypeScript type.
|
|
137
|
+
- read { id } → the data, as it was written. An id this conversation does not hold is an error.
|
|
138
|
+
- list → every entry held, without its data: how to find one written earlier.
|
|
139
|
+
- drop { id } → { dropped }.
|
|
140
|
+
|
|
141
|
+
Written and read from composed code, the data never passes through the conversation: write a tool's output where it is produced, and read it where it is used, by the id the write returned. Read by an id written as literal text, it is typed by what the entry holds.`;
|
|
142
|
+
|
|
143
|
+
// The description is the same in every conversation and every round: a tool definition that changed with
|
|
144
|
+
// each write would invalidate a provider's prompt cache for the whole conversation. What a conversation
|
|
145
|
+
// holds is found with `list`, and its types reach a check through `sessionType`.
|
|
146
|
+
export const sessionDataTool: Tool<unknown> = {
|
|
147
|
+
name: TOOL_NAME,
|
|
148
|
+
description: DESCRIPTION,
|
|
149
|
+
inputSchema: {
|
|
150
|
+
type: 'object',
|
|
151
|
+
required: ['action'],
|
|
152
|
+
properties: {
|
|
153
|
+
action: { type: 'string', enum: ['write', 'read', 'list', 'drop'] },
|
|
154
|
+
id: { type: 'string', description: 'read, drop: the id a write returned.' },
|
|
155
|
+
description: { type: 'string', description: 'write: what the data is.' },
|
|
156
|
+
data: { description: 'write: the value to keep, any JSON.' },
|
|
157
|
+
},
|
|
158
|
+
},
|
|
159
|
+
sessionType,
|
|
160
|
+
executor: { execute },
|
|
161
|
+
};
|
|
162
|
+
|
|
163
|
+
export const plugin: MatbotPluginSpec = {
|
|
164
|
+
apiVersion: PLUGIN_API_VERSION,
|
|
165
|
+
manifest: { description: 'Keep intermediate results in a conversation and read them back by id (`session_data`: write/read/list/drop).' },
|
|
166
|
+
tools: [sessionDataTool],
|
|
167
|
+
};
|
package/src/shape.ts
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
// The TypeScript type of a JSON value, as text: what a body reading an entry is checked against, and what
|
|
2
|
+
// the model is shown beside it. It is spliced into a type-check verbatim, so it must be valid TypeScript
|
|
3
|
+
// whatever it is given, and anything it cannot describe compactly is `unknown` — which a reader must narrow,
|
|
4
|
+
// rather than a guess it could rely on wrongly.
|
|
5
|
+
|
|
6
|
+
const IDENT = /^[A-Za-z_$][\w$]*$/;
|
|
7
|
+
const MAX_DEPTH = 8;
|
|
8
|
+
const MAX_UNION = 4;
|
|
9
|
+
const MAX_KEYS = 40;
|
|
10
|
+
const MAX_TEXT = 4000;
|
|
11
|
+
|
|
12
|
+
const key = (k: string): string => (IDENT.test(k) ? k : JSON.stringify(k));
|
|
13
|
+
|
|
14
|
+
const isRecord = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
15
|
+
|
|
16
|
+
function union(shapes: readonly string[]): string {
|
|
17
|
+
const distinct = [...new Set(shapes)];
|
|
18
|
+
return distinct.length > MAX_UNION ? 'unknown' : distinct.join(' | ');
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// `{}` is not the empty object type (it is "any non-nullish value"), so an empty object is spelt out.
|
|
22
|
+
function objectType(fields: readonly string[]): string {
|
|
23
|
+
return fields.length === 0 ? 'Record<string, never>' : `{ ${fields.join('; ')} }`;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// An array of objects is one object type, a key absent from some elements optional: the shape of a table,
|
|
27
|
+
// which is what a query hands back. Typed per element it would be a union as long as the table.
|
|
28
|
+
function rows(items: readonly Record<string, unknown>[], depth: number): string {
|
|
29
|
+
const seen = new Map<string, string[]>();
|
|
30
|
+
for (const item of items) {
|
|
31
|
+
for (const [k, v] of Object.entries(item)) {
|
|
32
|
+
const shapes = seen.get(k) ?? [];
|
|
33
|
+
shapes.push(shapeAt(v, depth + 1));
|
|
34
|
+
seen.set(k, shapes);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
if (seen.size > MAX_KEYS) return 'Record<string, unknown>';
|
|
38
|
+
return objectType([...seen].map(([k, shapes]) => `${key(k)}${shapes.length < items.length ? '?' : ''}: ${union(shapes)}`));
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function shapeAt(value: unknown, depth: number): string {
|
|
42
|
+
if (depth > MAX_DEPTH) return 'unknown';
|
|
43
|
+
if (value === null) return 'null';
|
|
44
|
+
switch (typeof value) {
|
|
45
|
+
case 'string': case 'number': case 'boolean': return typeof value;
|
|
46
|
+
default: break;
|
|
47
|
+
}
|
|
48
|
+
if (Array.isArray(value)) {
|
|
49
|
+
if (value.length === 0) return 'unknown[]';
|
|
50
|
+
if (value.every(isRecord)) return `${rows(value, depth)}[]`;
|
|
51
|
+
const element = union(value.map(v => shapeAt(v, depth + 1)));
|
|
52
|
+
return element.includes(' | ') ? `(${element})[]` : `${element}[]`;
|
|
53
|
+
}
|
|
54
|
+
if (isRecord(value)) {
|
|
55
|
+
const entries = Object.entries(value);
|
|
56
|
+
if (entries.length > MAX_KEYS) return 'Record<string, unknown>';
|
|
57
|
+
return objectType(entries.map(([k, v]) => `${key(k)}: ${shapeAt(v, depth + 1)}`));
|
|
58
|
+
}
|
|
59
|
+
return 'unknown';
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** The type of `value`, which is JSON (it has been through `JSON.parse`). */
|
|
63
|
+
export function shapeOf(value: unknown): string {
|
|
64
|
+
const text = shapeAt(value, 0);
|
|
65
|
+
return text.length <= MAX_TEXT ? text : (Array.isArray(value) ? 'unknown[]' : 'unknown');
|
|
66
|
+
}
|