@oortmem/decide-jev 0.0.0-stage → 0.1.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 ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,15 @@
1
- # Temporary Holding Version
1
+ # @oortmem/decide-jev
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Decides what happens to each new fact: add, update, supersede or skip. It uses TypeSafe Jev, which returns typed answers with probabilities.
4
+
5
+ ```sh
6
+ npm install @oortmem/decide-jev
7
+ ```
8
+
9
+ ```ts
10
+ import { jevDecider } from '@oortmem/decide-jev';
11
+
12
+ const decide = jevDecider({ apiKey: process.env.TYPESAFE_API_KEY });
13
+ ```
14
+
15
+ Part of [Oort](https://github.com/oortmem/oort), open-source memory for AI agents. See the [main README](https://github.com/oortmem/oort#readme) for how the pieces fit. Apache-2.0.
@@ -0,0 +1,47 @@
1
+ import { type DecisionController } from '@oortmem/core';
2
+ /** The slice of the TypeSafe client this adapter uses; inject a stub in tests. */
3
+ export interface SystemOneClient {
4
+ systemOne(req: {
5
+ state: unknown;
6
+ questions: Record<string, unknown>;
7
+ model?: string;
8
+ }): Promise<{
9
+ answers: Record<string, any>;
10
+ }>;
11
+ }
12
+ export type DecideErrorKind = 'auth' | 'rate-limit' | 'server' | 'network' | 'timeout' | 'bad-response';
13
+ /** A failed Jev call. The message never includes state, observation text, candidate text or the key. */
14
+ export declare class DecideError extends Error {
15
+ readonly kind: DecideErrorKind;
16
+ readonly status: number | undefined;
17
+ /** The Oort Pro relay's own message for a refusal (relay mode only); never a vendor body. */
18
+ readonly relayMessage: string | undefined;
19
+ constructor(kind: DecideErrorKind, status?: number, relayMessage?: string);
20
+ }
21
+ /**
22
+ * The Jev model the Oort Pro relay serves (`MODELS.decide` in apps/relay/src/relay.ts): the SDK's
23
+ * own default. Relay mode pins it, so `TYPESAFE_DEFAULT_MODEL` cannot pick a model the relay refuses.
24
+ */
25
+ export declare const RELAY_MODEL = "jev-latest";
26
+ export interface JevDeciderOptions {
27
+ /** Defaults to `process.env.TYPESAFE_API_KEY`. Ignored when `client` is given. */
28
+ apiKey?: string;
29
+ client?: SystemOneClient;
30
+ model?: string;
31
+ /**
32
+ * The TypeSafe SDK's `baseURL` (its default is `https://api.typesafe.ai`, or
33
+ * `TYPESAFE_BASE_URL`). The Oort Pro relay is `https://relay.oortcloud.dev/v1/typesafe`,
34
+ * with an Oort key as `apiKey` (the SDK sends `Authorization: Bearer`). Ignored with `client`.
35
+ */
36
+ baseURL?: string;
37
+ /** The SDK's fetch, for tests. Ignored with `client`. */
38
+ fetch?: typeof fetch;
39
+ /**
40
+ * The calls go through the Oort Pro relay. A 429 with `Retry-After` is retried once, as
41
+ * before; a 429 without it (the monthly cap) is not retried, and the relay's message is kept on
42
+ * the error as `relayMessage`.
43
+ */
44
+ relay?: boolean;
45
+ }
46
+ /** System One controller backed by TypeSafe's Jev model. One `systemOne` call per stage. */
47
+ export declare function jevDecider(opts?: JevDeciderOptions): DecisionController;
package/dist/index.js ADDED
@@ -0,0 +1,300 @@
1
+ import { APIConnectionError, APITimeoutError, AuthenticationError, InternalServerError, PermissionDeniedError, RateLimitError, TypeSafeClient, choice, noul, score, } from '@typesafe-ai/sdk';
2
+ import { MissingCredentialError, TOOL_SUMMARIES_MAX, TOOL_SUMMARY_MAX_BYTES, capUtf8, truncateUtf8, } from '@oortmem/core';
3
+ import { NOVEL_CRITERIA, NOVEL_INSTRUCTIONS, RECONCILE_CRITERIA, SALIENCE_INSTRUCTIONS, SALIENCE_LEVELS, SALIENCE_NAMES, SHOULD_STORE_INSTRUCTIONS, TYPE_INSTRUCTIONS, novelManyInstructions, reconcileInstructions, reconcileManyInstructions, } from './questions.js';
4
+ /** A failed Jev call. The message never includes state, observation text, candidate text or the key. */
5
+ export class DecideError extends Error {
6
+ kind;
7
+ status;
8
+ /** The Oort Pro relay's own message for a refusal (relay mode only); never a vendor body. */
9
+ relayMessage;
10
+ constructor(kind, status, relayMessage) {
11
+ super(relayMessage ??
12
+ `Jev decision call failed (${kind}${status === undefined ? '' : `, HTTP ${status}`})`);
13
+ this.name = 'DecideError';
14
+ this.kind = kind;
15
+ this.status = status;
16
+ this.relayMessage = relayMessage;
17
+ }
18
+ }
19
+ /** The `error` string of a relay refusal body, cleaned and cut short; undefined for anything else. */
20
+ function relayMessageOf(body) {
21
+ const msg = body?.error;
22
+ if (typeof msg !== 'string')
23
+ return undefined;
24
+ const clean = msg.replace(/[\u0000-\u001f\u007f]+/g, ' ').trim();
25
+ return clean === '' ? undefined : clean.slice(0, 400);
26
+ }
27
+ /**
28
+ * The Jev model the Oort Pro relay serves (`MODELS.decide` in apps/relay/src/relay.ts): the SDK's
29
+ * own default. Relay mode pins it, so `TYPESAFE_DEFAULT_MODEL` cannot pick a model the relay refuses.
30
+ */
31
+ export const RELAY_MODEL = 'jev-latest';
32
+ /** HTTP statuses the SDK retries on its own in relay mode: its default set, minus 429. */
33
+ const RELAY_RETRY_STATUSES = new Set([408, ...Array.from({ length: 100 }, (_, i) => 500 + i)]);
34
+ const MAX_RETRY_AFTER_MS = 5_000;
35
+ function fromStatus(status) {
36
+ if (status === 401 || status === 403)
37
+ return new DecideError('auth', status);
38
+ if (status === 429)
39
+ return new DecideError('rate-limit', status);
40
+ if (status >= 500)
41
+ return new DecideError('server', status);
42
+ return new DecideError('bad-response', status);
43
+ }
44
+ /** Maps anything the SDK or client throws to a DecideError, dropping its message and cause. */
45
+ function wrap(e, relay = false) {
46
+ if (e instanceof DecideError)
47
+ return e;
48
+ if (e instanceof RateLimitError && relay) {
49
+ return new DecideError('rate-limit', e.status, relayMessageOf(e.body));
50
+ }
51
+ if (e instanceof AuthenticationError || e instanceof PermissionDeniedError) {
52
+ return new DecideError('auth', e.status);
53
+ }
54
+ if (e instanceof RateLimitError)
55
+ return new DecideError('rate-limit', e.status);
56
+ if (e instanceof InternalServerError)
57
+ return new DecideError('server', e.status);
58
+ if (e instanceof APITimeoutError)
59
+ return new DecideError('timeout');
60
+ if (e instanceof APIConnectionError)
61
+ return new DecideError('network');
62
+ if (typeof e === 'object' && e !== null) {
63
+ const status = e.status;
64
+ if (typeof status === 'number')
65
+ return fromStatus(status);
66
+ const name = e.name;
67
+ if (name === 'TimeoutError' || name === 'AbortError')
68
+ return new DecideError('timeout');
69
+ }
70
+ return new DecideError('network');
71
+ }
72
+ const bad = () => new DecideError('bad-response');
73
+ function isObj(x) {
74
+ return typeof x === 'object' && x !== null;
75
+ }
76
+ const isProb = (x) => typeof x === 'number' && Number.isFinite(x);
77
+ function noulOf(answers, id) {
78
+ const a = answers[id];
79
+ if (!isObj(a) || a['type'] !== 'noul' || !isProb(a['noul']))
80
+ throw bad();
81
+ return a['noul'];
82
+ }
83
+ function scoreOf(answers, id) {
84
+ const a = answers[id];
85
+ if (!isObj(a) || a['type'] !== 'score' || !isProb(a['score']) || !isObj(a['probabilities'])) {
86
+ throw bad();
87
+ }
88
+ return { score: a['score'], probabilities: a['probabilities'] };
89
+ }
90
+ const ACTIONS = new Set(['NOOP', 'REINFORCE', 'ADD', 'UPDATE', 'SUPERSEDE']);
91
+ function choiceOf(answers, id) {
92
+ const a = answers[id];
93
+ if (!isObj(a) || a['type'] !== 'choice' || !isObj(a['probabilities']))
94
+ throw bad();
95
+ const c = a['choice'];
96
+ if (typeof c !== 'string' || !ACTIONS.has(c))
97
+ throw bad();
98
+ const p = a['probabilities'][c];
99
+ if (!isProb(p))
100
+ throw bad();
101
+ return { action: c, probability: p };
102
+ }
103
+ const clamp = (x, lo, hi) => Math.min(hi, Math.max(lo, x));
104
+ const MEMORY_TYPES = ['semantic', 'episodic', 'procedural', 'preference'];
105
+ /**
106
+ * Keeps one Jev request body well under the relay's 64 KB limit (56 KB with the questions):
107
+ * user and assistant text 16 KB each (head and tail), a candidate memory's text 1 KB.
108
+ */
109
+ const STATE_TEXT_MAX_BYTES = 16 * 1024;
110
+ const CANDIDATE_TEXT_MAX_BYTES = 1024;
111
+ function obsState(obs) {
112
+ return {
113
+ user: capUtf8(obs.userText, STATE_TEXT_MAX_BYTES),
114
+ assistant: capUtf8(obs.assistantText, STATE_TEXT_MAX_BYTES),
115
+ tools: obs.toolSummaries
116
+ .slice(0, TOOL_SUMMARIES_MAX)
117
+ .map((t) => truncateUtf8(t, TOOL_SUMMARY_MAX_BYTES)),
118
+ at: obs.at,
119
+ };
120
+ }
121
+ /** System One controller backed by TypeSafe's Jev model. One `systemOne` call per stage. */
122
+ export function jevDecider(opts = {}) {
123
+ let client = opts.client;
124
+ if (client === undefined) {
125
+ const apiKey = opts.apiKey ?? process.env['TYPESAFE_API_KEY'];
126
+ if (apiKey === undefined || apiKey === '') {
127
+ throw new MissingCredentialError('TYPESAFE_API_KEY', 'decide.apiKey');
128
+ }
129
+ client = new TypeSafeClient({
130
+ apiKey,
131
+ ...(opts.baseURL !== undefined && { baseURL: opts.baseURL }),
132
+ ...(opts.fetch !== undefined && { fetch: opts.fetch }),
133
+ // The SDK would retry every 429 (twice); here a cap 429 must not be retried. It keeps its
134
+ // retries for 408 and 5xx, and `ask` makes the one retry for a 429 with Retry-After.
135
+ // The relay checks the body, so it takes only plain JSON (no zstd) and its pinned model.
136
+ ...(opts.relay === true && {
137
+ retry: { httpStatuses: RELAY_RETRY_STATUSES },
138
+ compression: false,
139
+ defaultModel: RELAY_MODEL,
140
+ }),
141
+ });
142
+ }
143
+ const c = client;
144
+ async function ask(state, questions) {
145
+ try {
146
+ const req = { state, questions, ...(opts.model === undefined ? {} : { model: opts.model }) };
147
+ let res;
148
+ try {
149
+ res = await c.systemOne(req);
150
+ }
151
+ catch (e) {
152
+ const wait = e instanceof RateLimitError && opts.relay === true ? e.retryAfterMs : undefined;
153
+ if (wait === undefined)
154
+ throw e;
155
+ await new Promise((r) => setTimeout(r, Math.min(wait, MAX_RETRY_AFTER_MS)));
156
+ res = await c.systemOne(req);
157
+ }
158
+ if (!isObj(res) || !isObj(res.answers))
159
+ throw bad();
160
+ return res.answers;
161
+ }
162
+ catch (e) {
163
+ throw wrap(e, opts.relay === true);
164
+ }
165
+ }
166
+ return {
167
+ async gate(obs) {
168
+ const questions = {
169
+ should_store: noul(SHOULD_STORE_INSTRUCTIONS),
170
+ salience: score(SALIENCE_INSTRUCTIONS, [...SALIENCE_LEVELS]),
171
+ };
172
+ for (const t of MEMORY_TYPES)
173
+ questions[`type_${t}`] = noul(TYPE_INSTRUCTIONS[t]);
174
+ const answers = await ask(obsState(obs), questions);
175
+ const decisions = [];
176
+ const yesNo = (question, p) => decisions.push({
177
+ stage: 'gate',
178
+ question,
179
+ answer: p >= 0.5 ? 'yes' : 'no',
180
+ probability: p,
181
+ });
182
+ const shouldStore = noulOf(answers, 'should_store');
183
+ yesNo('should_store', shouldStore);
184
+ const sal = scoreOf(answers, 'salience');
185
+ const s = clamp(sal.score, 0, 3);
186
+ const level = Math.round(s);
187
+ const lp = sal.probabilities[String(level)];
188
+ if (!isProb(lp))
189
+ throw bad();
190
+ decisions.push({
191
+ stage: 'gate',
192
+ question: 'salience',
193
+ answer: SALIENCE_NAMES[level],
194
+ probability: lp,
195
+ });
196
+ const types = {};
197
+ for (const t of MEMORY_TYPES) {
198
+ const p = noulOf(answers, `type_${t}`);
199
+ types[t] = p;
200
+ yesNo(`type_${t}`, p);
201
+ }
202
+ return { shouldStore, salience: 0.1 + 0.3 * s, types, decisions };
203
+ },
204
+ async reconcile(obs, candidates) {
205
+ const one = (question, candidateId, a) => ({
206
+ candidateId,
207
+ action: a.action,
208
+ probability: a.probability,
209
+ decisions: [{ stage: 'reconcile', question, answer: a.action, probability: a.probability }],
210
+ });
211
+ if (candidates.length === 0) {
212
+ const answers = await ask({ observation: obsState(obs), candidates: [] }, { novel: choice(NOVEL_INSTRUCTIONS, NOVEL_CRITERIA) });
213
+ return [one('novel', null, choiceOf(answers, 'novel'))];
214
+ }
215
+ const questions = {};
216
+ candidates.forEach((_, i) => {
217
+ questions[`c${i}`] = choice(reconcileInstructions(i), RECONCILE_CRITERIA);
218
+ });
219
+ const state = {
220
+ observation: obsState(obs),
221
+ candidates: candidates.map((m) => ({
222
+ id: m.id,
223
+ text: truncateUtf8(m.text, CANDIDATE_TEXT_MAX_BYTES),
224
+ type: m.type,
225
+ validFrom: m.validFrom,
226
+ })),
227
+ };
228
+ const answers = await ask(state, questions);
229
+ return candidates.map((m, i) => one(`c${i}`, m.id, choiceOf(answers, `c${i}`)));
230
+ },
231
+ async reconcileMany(items) {
232
+ // One call for several facts, split where one request would outgrow the size cap.
233
+ const out = [];
234
+ let chunk = [];
235
+ const flush = async () => {
236
+ if (chunk.length === 0)
237
+ return;
238
+ out.push(...(await reconcileChunk(chunk.map((j) => items[j]))));
239
+ chunk = [];
240
+ };
241
+ for (let j = 0; j < items.length; j++) {
242
+ const next = [...chunk, j].map((k) => items[k]);
243
+ if (chunk.length > 0 && requestBytes(manyRequest(next)) > MANY_REQUEST_MAX_BYTES)
244
+ await flush();
245
+ chunk.push(j);
246
+ }
247
+ await flush();
248
+ return out;
249
+ },
250
+ };
251
+ async function reconcileChunk(items) {
252
+ const { state, questions } = manyRequest(items);
253
+ const answers = await ask(state, questions);
254
+ return items.map((it, j) => {
255
+ const one = (question, candidateId) => {
256
+ const a = choiceOf(answers, question);
257
+ return {
258
+ candidateId,
259
+ action: a.action,
260
+ probability: a.probability,
261
+ decisions: [
262
+ { stage: 'reconcile', question, answer: a.action, probability: a.probability },
263
+ ],
264
+ };
265
+ };
266
+ if (it.candidates.length === 0)
267
+ return [one(`f${j}_novel`, null)];
268
+ return it.candidates.map((m, i) => one(`f${j}_c${i}`, m.id));
269
+ });
270
+ }
271
+ }
272
+ /** Keeps a batched reconcile body under the relay's 56 KB, with room for the request envelope. */
273
+ const MANY_REQUEST_MAX_BYTES = 48 * 1024;
274
+ const requestBytes = (r) => new TextEncoder().encode(JSON.stringify(r)).byteLength;
275
+ function manyRequest(items) {
276
+ const questions = {};
277
+ items.forEach((it, j) => {
278
+ if (it.candidates.length === 0) {
279
+ questions[`f${j}_novel`] = choice(novelManyInstructions(j), NOVEL_CRITERIA);
280
+ }
281
+ else {
282
+ it.candidates.forEach((_, i) => {
283
+ questions[`f${j}_c${i}`] = choice(reconcileManyInstructions(j, i), RECONCILE_CRITERIA);
284
+ });
285
+ }
286
+ });
287
+ const state = {
288
+ facts: items.map((it) => ({
289
+ observation: obsState(it.obs),
290
+ candidates: it.candidates.map((m) => ({
291
+ id: m.id,
292
+ text: truncateUtf8(m.text, CANDIDATE_TEXT_MAX_BYTES),
293
+ type: m.type,
294
+ validFrom: m.validFrom,
295
+ })),
296
+ })),
297
+ };
298
+ return { state, questions };
299
+ }
300
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,33 @@
1
+ /**
2
+ * The questions Jev answers. Question ids are not sent to the model, so every
3
+ * instruction must stand on its own. Later calibration work tunes this file.
4
+ */
5
+ export declare const SHOULD_STORE_INSTRUCTIONS = "Does this exchange between a developer and an AI coding assistant contain a fact, decision, preference, or reusable procedure that would be useful to remember in a future session? Small talk, acknowledgements, and transient progress updates are not.";
6
+ export declare const SALIENCE_INSTRUCTIONS = "How important would it be for the assistant to remember this in future sessions?";
7
+ /** Ordered low to high; the gate maps score 0..3 to salience 0.1..1.0. */
8
+ export declare const SALIENCE_LEVELS: readonly ['trivial: no lasting value', 'useful: nice to recall but not essential', 'important: changes how future work should be done', 'critical: forgetting it would cause a mistake or repeated work'];
9
+ /** Short names of the salience levels, in the same order as SALIENCE_LEVELS. */
10
+ export declare const SALIENCE_NAMES: readonly ['trivial', 'useful', 'important', 'critical'];
11
+ export declare const TYPE_INSTRUCTIONS: {
12
+ readonly semantic: 'Does this exchange contain a durable fact about a codebase, system, product or person that would stay true across sessions?';
13
+ readonly episodic: 'Does this exchange describe a specific event or incident at a point in time, such as a debugging session or a decision made on a particular day?';
14
+ readonly procedural: 'Does this exchange contain a reusable how-to, such as a command sequence, workflow or playbook for getting something done?';
15
+ readonly preference: 'Does this exchange contain a stated preference or rule for style, tools or communication that the assistant should follow in future?';
16
+ };
17
+ export declare function reconcileInstructions(i: number): string;
18
+ /** `reconcileInstructions` for fact `j` of a batched request (CON-56). */
19
+ export declare function reconcileManyInstructions(j: number, i: number): string;
20
+ /** `NOVEL_INSTRUCTIONS` for fact `j` of a batched request. */
21
+ export declare function novelManyInstructions(j: number): string;
22
+ export declare const RECONCILE_CRITERIA: {
23
+ readonly NOOP: 'unrelated: the observation is about something else';
24
+ readonly REINFORCE: 'restates or confirms the memory with no new information';
25
+ readonly UPDATE: 'adds detail to or refines the memory without contradicting it';
26
+ readonly SUPERSEDE: 'states that the memory is no longer true; the situation changed or the memory was wrong';
27
+ readonly ADD: 'touches the same subject but carries a separate new fact that should be stored on its own';
28
+ };
29
+ export declare const NOVEL_INSTRUCTIONS = "Does the new observation contain information worth storing as a new memory?";
30
+ export declare const NOVEL_CRITERIA: {
31
+ readonly ADD: 'yes, it contains a new fact, decision, preference or procedure';
32
+ readonly NOOP: 'no, nothing new worth storing';
33
+ };
@@ -0,0 +1,45 @@
1
+ /**
2
+ * The questions Jev answers. Question ids are not sent to the model, so every
3
+ * instruction must stand on its own. Later calibration work tunes this file.
4
+ */
5
+ export const SHOULD_STORE_INSTRUCTIONS = 'Does this exchange between a developer and an AI coding assistant contain a fact, decision, preference, or reusable procedure that would be useful to remember in a future session? Small talk, acknowledgements, and transient progress updates are not.';
6
+ export const SALIENCE_INSTRUCTIONS = 'How important would it be for the assistant to remember this in future sessions?';
7
+ /** Ordered low to high; the gate maps score 0..3 to salience 0.1..1.0. */
8
+ export const SALIENCE_LEVELS = [
9
+ 'trivial: no lasting value',
10
+ 'useful: nice to recall but not essential',
11
+ 'important: changes how future work should be done',
12
+ 'critical: forgetting it would cause a mistake or repeated work',
13
+ ];
14
+ /** Short names of the salience levels, in the same order as SALIENCE_LEVELS. */
15
+ export const SALIENCE_NAMES = ['trivial', 'useful', 'important', 'critical'];
16
+ export const TYPE_INSTRUCTIONS = {
17
+ semantic: 'Does this exchange contain a durable fact about a codebase, system, product or person that would stay true across sessions?',
18
+ episodic: 'Does this exchange describe a specific event or incident at a point in time, such as a debugging session or a decision made on a particular day?',
19
+ procedural: 'Does this exchange contain a reusable how-to, such as a command sequence, workflow or playbook for getting something done?',
20
+ preference: 'Does this exchange contain a stated preference or rule for style, tools or communication that the assistant should follow in future?',
21
+ };
22
+ export function reconcileInstructions(i) {
23
+ return `How does the new observation relate to the existing memory at \`candidates[${i}]\`? Judge only this one memory.`;
24
+ }
25
+ /** `reconcileInstructions` for fact `j` of a batched request (CON-56). */
26
+ export function reconcileManyInstructions(j, i) {
27
+ return `How does the new fact at \`facts[${j}].observation\` relate to the existing memory at \`facts[${j}].candidates[${i}]\`? Judge only this fact and this one memory.`;
28
+ }
29
+ /** `NOVEL_INSTRUCTIONS` for fact `j` of a batched request. */
30
+ export function novelManyInstructions(j) {
31
+ return `Does the new fact at \`facts[${j}].observation\` contain information worth storing as a new memory?`;
32
+ }
33
+ export const RECONCILE_CRITERIA = {
34
+ NOOP: 'unrelated: the observation is about something else',
35
+ REINFORCE: 'restates or confirms the memory with no new information',
36
+ UPDATE: 'adds detail to or refines the memory without contradicting it',
37
+ SUPERSEDE: 'states that the memory is no longer true; the situation changed or the memory was wrong',
38
+ ADD: 'touches the same subject but carries a separate new fact that should be stored on its own',
39
+ };
40
+ export const NOVEL_INSTRUCTIONS = 'Does the new observation contain information worth storing as a new memory?';
41
+ export const NOVEL_CRITERIA = {
42
+ ADD: 'yes, it contains a new fact, decision, preference or procedure',
43
+ NOOP: 'no, nothing new worth storing',
44
+ };
45
+ //# sourceMappingURL=questions.js.map
package/package.json CHANGED
@@ -1,6 +1,59 @@
1
1
  {
2
2
  "name": "@oortmem/decide-jev",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Oort decisions: add, update, supersede or skip, using TypeSafe Jev.",
5
+ "keywords": [
6
+ "oort",
7
+ "agent-memory",
8
+ "ai-agents",
9
+ "llm-memory",
10
+ "typesafe",
11
+ "jev",
12
+ "decision"
13
+ ],
14
+ "homepage": "https://oortcloud.dev",
15
+ "bugs": {
16
+ "url": "https://github.com/oortmem/oort/issues",
17
+ "email": "hello@oortcloud.dev"
18
+ },
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "git+https://github.com/oortmem/oort.git",
22
+ "directory": "packages/decide-jev"
23
+ },
24
+ "license": "Apache-2.0",
25
+ "author": "Oort <hello@oortcloud.dev>",
26
+ "type": "module",
27
+ "engines": {
28
+ "node": ">=22.15.0"
29
+ },
30
+ "sideEffects": false,
31
+ "main": "./dist/index.js",
32
+ "types": "./dist/index.d.ts",
33
+ "exports": {
34
+ ".": {
35
+ "types": "./dist/index.d.ts",
36
+ "default": "./dist/index.js"
37
+ }
38
+ },
39
+ "files": [
40
+ "dist",
41
+ "!dist/**/*.map",
42
+ "README.md",
43
+ "LICENSE"
44
+ ],
45
+ "publishConfig": {
46
+ "access": "public"
47
+ },
48
+ "dependencies": {
49
+ "@oortmem/core": "0.1.0",
50
+ "@typesafe-ai/sdk": "0.7.0"
51
+ },
52
+ "devDependencies": {
53
+ "vitest": "^5.0.5"
54
+ },
55
+ "scripts": {
56
+ "build": "tsc -p tsconfig.json",
57
+ "typecheck": "tsc -p tsconfig.typecheck.json"
58
+ }
6
59
  }