@harny/vercel-ai-provider 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,142 @@
1
- # Temporary Holding Version
1
+ # @harny/vercel-ai-provider
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
+ Long-term memory for the Vercel AI SDK: wrap any model with `harny(model)` and it remembers each person across every conversation.
4
+
5
+ ## For an AI coding agent: what to do
6
+
7
+ 1. Install: `npm install @harny/vercel-ai-provider ai` (needs `ai` 7, Node 20 or newer).
8
+ 2. Get a key (see "No key yet?" below) and set `HARNY_API_KEY`.
9
+ 3. Wrap the model you already use and name the person: `harny(openai('gpt-5'), { user: 'nadia' })`.
10
+ 4. Do not write your own memory code, prompt stuffing or vector store. This package recalls before the call; saving what the person says is off until you switch it on (`saveUserMessages: true`).
11
+
12
+ ## One minute
13
+
14
+ ```ts
15
+ import { generateText } from 'ai';
16
+ import { openai } from '@ai-sdk/openai';
17
+ import { createHarny } from '@harny/vercel-ai-provider';
18
+
19
+ const harny = createHarny(); // reads HARNY_API_KEY
20
+
21
+ const { text } = await generateText({
22
+ model: harny(openai('gpt-5'), { user: 'nadia' }), // your id for the person
23
+ prompt: 'What is the Acme pilot budget?',
24
+ });
25
+ ```
26
+
27
+ Before each call it recalls what Harny holds for `nadia` and adds it to the system prompt. Saving conversation messages is off by default; add `saveUserMessages: true` to the settings to store what Nadia says after each successful call, or save facts yourself with `harny.ingest` (below).
28
+
29
+ ## The canonical example
30
+
31
+ Send two dated facts, wait until they are ready, recall as one person. Same facts and ids as the Python SDK example below.
32
+
33
+ ```ts
34
+ import { createHarny } from '@harny/vercel-ai-provider';
35
+
36
+ const harny = createHarny({ user: 'nadia' }); // reads HARNY_API_KEY
37
+
38
+ await harny.ingest({
39
+ content: 'Nadia confirmed the Acme pilot ships March 14. Budget is 32k.',
40
+ id: 'call-8820',
41
+ label: 'Account review call',
42
+ timestamp: '2026-02-03T09:00:00Z',
43
+ });
44
+ const receipt = await harny.ingest({
45
+ content: 'Nadia raised the Acme pilot budget from 32k to 40k.',
46
+ id: 'call-8821',
47
+ label: 'Budget change',
48
+ timestamp: '2026-03-01T09:00:00Z',
49
+ });
50
+ await harny.waitForIngestion(receipt.ingestionId);
51
+
52
+ const recall = await harny.recall({ query: 'What is the Acme pilot budget?', level: 'medium' });
53
+ for (const result of recall.results) console.log(result.rank, result.content);
54
+ ```
55
+
56
+ The newest fact wins: the answer says 40k. Sending the same `id` again replaces the data point; sending the same text again is free.
57
+
58
+ ## Give the model tools instead (or as well)
59
+
60
+ ```ts
61
+ import { generateText, stepCountIs } from 'ai';
62
+ import { createHarny } from '@harny/vercel-ai-provider';
63
+
64
+ const harny = createHarny({ user: 'nadia' });
65
+
66
+ const result = await generateText({
67
+ model: yourModel,
68
+ tools: harny.tools(), // { harny_remember, harny_recall }
69
+ stopWhen: stepCountIs(5),
70
+ prompt: 'Remember that Nadia prefers async standups.',
71
+ });
72
+ ```
73
+
74
+ The person is fixed by you (`createHarny({ user })` or `harny.tools({ user })`). The model cannot choose whose memory it reads.
75
+
76
+ ## API
77
+
78
+ | Call | What it does |
79
+ | --- | --- |
80
+ | `createHarny({ apiKey?, baseURL?, user?, fetch? })` | The provider. `apiKey` defaults to `HARNY_API_KEY`, `baseURL` to `HARNY_API_URL`, else `https://api.harny.ai` (`/v1` is added; plain http only for localhost). |
81
+ | `harny(model, settings?)` | Wraps a model object (or a gateway id such as `'openai/gpt-5'`). Settings: `user`, `recall`, `level` / `maxTokens`, `limit`, `saveUserMessages`, `conversationId`, `heading`, `formatMemories`, `metadata`, `onError`, `onPending`, `waitUntil`, `cacheTtlMs`. |
82
+ | `harny.middleware(settings?)` | The same memory as a middleware for `wrapLanguageModel`. |
83
+ | `harny.tools(settings?)` | `{ harny_remember, harny_recall }` for a tool set. |
84
+ | `harny.ingest`, `ingestBatch`, `getIngestion`, `waitForIngestion`, `deleteIngestion`, `deleteDataPoints`, `recall`, `usage` | The memory API, one method per route. |
85
+ | `addMemories(messages, opts)` | Store the user messages of a prompt-shaped array. Assistant and system messages are skipped. |
86
+ | `retrieveMemories(prompt, opts)` | A system-prompt block with the recalled memories (`''` when none). |
87
+ | `getMemories(prompt, opts)` | The raw recalled results. |
88
+ | `HarnyAPIError` | `code`, `status`, `debugMessage`, `data`, `retryAfter` (seconds), `requestId`. |
89
+
90
+ ## How it behaves
91
+
92
+ - **Saving conversation messages is off by default.** Switch it on with `saveUserMessages: true`; then only what the person says is stored, never what the model says. `addMemories` and the `harny_remember` tool save on request.
93
+ - **Idempotent ids.** A stored message gets the id `turn-` plus the SHA-256 of the conversation key and the text. The conversation key is your `conversationId`, else a hash of the first user message. A repeat replaces itself and costs nothing.
94
+ - **Memory never fails the call.** If recall or storing fails, the model call still runs and the error goes to `onError(error, { stage })`.
95
+ - **Fresh facts.** If recall reports sends still being processed, `onPending(pending)` is called, so you can tell the person the newest facts may be missing.
96
+ - **Tool loops.** Recall is reused for the same person and question for 30 seconds (`cacheTtlMs`); steps that only continue a tool call store nothing new.
97
+ - **Serverless.** Pass `waitUntil` (for example Vercel's) to store after the response is sent. Without it, the call waits for the store.
98
+ - **Errors.** Every refusal is a `HarnyAPIError` with the API's `code`. A per-minute 429 has no body: read `retryAfter`.
99
+
100
+ ## The memory API underneath
101
+
102
+ Everything above is a thin wrapper over `/v1/memory` (ingest, status, delete, recall, usage). The Python SDK serves the same example; the TypeScript above does the same calls.
103
+
104
+ ```python
105
+ from harny import SyncHarnyClient
106
+
107
+ with SyncHarnyClient() as harny: # reads HARNY_API_KEY
108
+ harny.ingest_data_point(
109
+ "Nadia confirmed the Acme pilot ships March 14. Budget is 32k.",
110
+ id="call-8820", label="Account review call", timestamp="2026-02-03T09:00:00Z", user="nadia",
111
+ )
112
+ receipt = harny.ingest_data_point(
113
+ "Nadia raised the Acme pilot budget from 32k to 40k.",
114
+ id="call-8821", label="Budget change", timestamp="2026-03-01T09:00:00Z", user="nadia",
115
+ )
116
+ harny.wait_for_ingestion(receipt.ingestionId, user="nadia")
117
+
118
+ recall = harny.recall("What is the Acme pilot budget?", level="medium", user="nadia")
119
+ for result in recall.results:
120
+ print(result.rank, result.content)
121
+ ```
122
+
123
+ ## No key yet?
124
+
125
+ Make an app and save its key to `.env` without printing it:
126
+
127
+ ```bash
128
+ pip install harny
129
+ harny init --name "<business>" --about "<what the app does>" --customers "<who its customers are>" --preset cost_first
130
+ ```
131
+
132
+ Or call `POST https://api.harny.ai/v1/auth/provision` with `{"app_name": "my-agent"}`; the answer holds an app key (`fsa_...`) shown once. Keep it in `HARNY_API_KEY`. Never print it or commit it. An app key needs `user`; a person's own key (`fsk_...`) does not.
133
+
134
+ ## Tested against
135
+
136
+ - `ai@7.0.156` and `@ai-sdk/provider@4.0.34` (pinned in `package-lock.json`).
137
+ - `bash scripts/ci.sh` installs those exact versions, builds, type-checks and runs the tests with no network. `bash scripts/ci.sh --latest` also tries the newest `ai` and `@ai-sdk/provider` and reports separately, so a framework update cannot break the package silently.
138
+ - Development needs Node 20.19 or newer (npm 10.8 or newer).
139
+
140
+ ## Licence
141
+
142
+ Apache-2.0. See `LICENSE`.
@@ -0,0 +1,46 @@
1
+ import type { BatchIngestReceipt, DataPointInput, DeleteReceipt, HarnyClientOptions, IngestReceipt, IngestionStatus, RecallOptions, RecallResponse, UsageResponse } from './types.js';
2
+ export declare const DEFAULT_BASE_URL = "https://api.harny.ai";
3
+ /** Add `/v1` when missing; refuse plain http unless the host is localhost or a loopback address. */
4
+ export declare function resolveBaseURL(baseURL?: string): string;
5
+ /** A thin client over the eight `/v1/memory` routes. It holds no state besides its options. */
6
+ export declare class HarnyClient {
7
+ private readonly options;
8
+ constructor(options?: HarnyClientOptions);
9
+ private key;
10
+ /** The end user for a call: the call's own, else the one given to createHarny. */
11
+ actingUser(user?: string): string | undefined;
12
+ private needUser;
13
+ private request;
14
+ /** Send one data point. The same `id` with changed text replaces the old; the same text again is `unchanged`. */
15
+ ingest(input: DataPointInput & {
16
+ idempotencyKey?: string;
17
+ user?: string;
18
+ }): Promise<IngestReceipt>;
19
+ /** Send 1 to 1,000 data points. Retry with the same `idempotencyKey` to resume where it stopped. */
20
+ ingestBatch(items: DataPointInput[], options?: {
21
+ idempotencyKey?: string;
22
+ user?: string;
23
+ }): Promise<BatchIngestReceipt>;
24
+ getIngestion(ingestionId: string, options?: {
25
+ user?: string;
26
+ }): Promise<IngestionStatus>;
27
+ /** Poll until the send is `completed` or `failed`. Throws a `timeout` HarnyAPIError after `timeoutMs`. */
28
+ waitForIngestion(ingestionId: string, options?: {
29
+ user?: string;
30
+ timeoutMs?: number;
31
+ pollMs?: number;
32
+ sleep?: (ms: number) => Promise<void>;
33
+ }): Promise<IngestionStatus>;
34
+ /** Forget every data point of one send. Repeating the call is safe. */
35
+ deleteIngestion(ingestionId: string, options?: {
36
+ user?: string;
37
+ }): Promise<void>;
38
+ /** Forget 1 to 1,000 data points by `sourceId`. If one id is unknown, none is deleted and the error names it. */
39
+ deleteDataPoints(ids: string[], options?: {
40
+ user?: string;
41
+ }): Promise<DeleteReceipt>;
42
+ /** Ranked, dated evidence for a question, as the named person. */
43
+ recall(options: RecallOptions): Promise<RecallResponse>;
44
+ /** This month's use of the app. Needs the app key. */
45
+ usage(): Promise<UsageResponse>;
46
+ }
package/dist/client.js ADDED
@@ -0,0 +1,266 @@
1
+ import { HarnyAPIError, HarnyConfigError } from './errors.js';
2
+ export const DEFAULT_BASE_URL = 'https://api.harny.ai';
3
+ const LEVELS = ['low', 'medium', 'high', 'extra-high'];
4
+ const SORTS = ['relevance', 'chronological'];
5
+ const MIN_MAX_TOKENS = 256;
6
+ const MAX_BATCH_ITEMS = 1000;
7
+ function env(name) {
8
+ const value = typeof process !== 'undefined' ? process.env?.[name] : undefined;
9
+ return value && value.trim() ? value.trim() : undefined;
10
+ }
11
+ /** Add `/v1` when missing; refuse plain http unless the host is localhost or a loopback address. */
12
+ export function resolveBaseURL(baseURL) {
13
+ const raw = (baseURL ?? env('HARNY_API_URL') ?? DEFAULT_BASE_URL).trim();
14
+ let url;
15
+ try {
16
+ url = new URL(raw);
17
+ }
18
+ catch {
19
+ throw new HarnyConfigError(`baseURL must be an absolute https URL, got ${JSON.stringify(raw)}`);
20
+ }
21
+ const host = url.hostname.toLowerCase();
22
+ const loopback = host === 'localhost' || host === '127.0.0.1' || host === '[::1]' || host.endsWith('.localhost');
23
+ if (url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback)) {
24
+ throw new HarnyConfigError('baseURL must use https unless the host is localhost or a loopback address');
25
+ }
26
+ const path = url.pathname.replace(/\/+$/, '');
27
+ const full = path.endsWith('/v1') ? path : `${path}/v1`;
28
+ return `${url.origin}${full}`;
29
+ }
30
+ function iso(value, name) {
31
+ if (value instanceof Date) {
32
+ if (Number.isNaN(value.getTime()))
33
+ throw new HarnyConfigError(`${name} is not a valid date`);
34
+ return value.toISOString();
35
+ }
36
+ if (typeof value !== 'string' || !value.trim()) {
37
+ throw new HarnyConfigError(`${name} must be an ISO 8601 string with a zone, or a Date`);
38
+ }
39
+ return value.trim();
40
+ }
41
+ function dataPointBody(input) {
42
+ if (typeof input.content !== 'string' || !input.content.trim()) {
43
+ throw new HarnyConfigError('content must be a non-blank string');
44
+ }
45
+ const body = { content: input.content };
46
+ if (input.id !== undefined) {
47
+ if (!input.id || input.id.includes('/'))
48
+ throw new HarnyConfigError("id must be a non-empty string without '/'");
49
+ body.id = input.id;
50
+ }
51
+ if (input.label !== undefined)
52
+ body.label = input.label;
53
+ if (input.timestamp !== undefined)
54
+ body.timestamp = iso(input.timestamp, 'timestamp');
55
+ if (input.metadata !== undefined)
56
+ body.metadata = input.metadata;
57
+ return body;
58
+ }
59
+ function recallBody(options, identity) {
60
+ if (typeof options.query !== 'string' || !options.query.trim()) {
61
+ throw new HarnyConfigError('query must be a non-blank string');
62
+ }
63
+ if (options.level !== undefined && options.maxTokens !== undefined) {
64
+ throw new HarnyConfigError('pass level or maxTokens, not both');
65
+ }
66
+ const body = { query: options.query, identity };
67
+ if (options.level !== undefined) {
68
+ if (!LEVELS.includes(options.level))
69
+ throw new HarnyConfigError(`level must be one of ${LEVELS.join(', ')}`);
70
+ body.level = options.level;
71
+ }
72
+ if (options.maxTokens !== undefined) {
73
+ if (!Number.isInteger(options.maxTokens) || options.maxTokens < MIN_MAX_TOKENS) {
74
+ throw new HarnyConfigError(`maxTokens must be an integer of at least ${MIN_MAX_TOKENS}`);
75
+ }
76
+ body.maxTokens = options.maxTokens;
77
+ }
78
+ if (options.limit !== undefined) {
79
+ if (!Number.isInteger(options.limit) || options.limit < 1 || options.limit > 200) {
80
+ throw new HarnyConfigError('limit must be an integer from 1 to 200');
81
+ }
82
+ body.limit = options.limit;
83
+ }
84
+ if (options.sort !== undefined) {
85
+ if (!SORTS.includes(options.sort))
86
+ throw new HarnyConfigError(`sort must be one of ${SORTS.join(', ')}`);
87
+ body.sort = options.sort;
88
+ }
89
+ if (options.queryTimestamp !== undefined)
90
+ body.queryTimestamp = iso(options.queryTimestamp, 'queryTimestamp');
91
+ if (options.occurredFrom !== undefined)
92
+ body.occurredFrom = iso(options.occurredFrom, 'occurredFrom');
93
+ if (options.occurredTo !== undefined)
94
+ body.occurredTo = iso(options.occurredTo, 'occurredTo');
95
+ return body;
96
+ }
97
+ /** A thin client over the eight `/v1/memory` routes. It holds no state besides its options. */
98
+ export class HarnyClient {
99
+ options;
100
+ constructor(options = {}) {
101
+ this.options = options;
102
+ }
103
+ key() {
104
+ const key = this.options.apiKey?.trim() || env('HARNY_API_KEY');
105
+ if (!key) {
106
+ throw new HarnyConfigError('No Harny key. Pass apiKey to createHarny or set HARNY_API_KEY. ' +
107
+ 'To get one: pip install harny, then harny init --name "<business>" (it saves the key to .env without printing it).');
108
+ }
109
+ return key;
110
+ }
111
+ /** The end user for a call: the call's own, else the one given to createHarny. */
112
+ actingUser(user) {
113
+ const named = (user ?? this.options.user)?.trim();
114
+ return named || undefined;
115
+ }
116
+ needUser(user) {
117
+ const named = this.actingUser(user);
118
+ if (!named) {
119
+ throw new HarnyConfigError("Name the end user: pass user: '<your id for the person>' to createHarny or to the call.");
120
+ }
121
+ return named;
122
+ }
123
+ async request(method, path, init = {}) {
124
+ const key = this.key();
125
+ const headers = { Authorization: `Bearer ${key}`, Accept: 'application/json' };
126
+ if (init.body !== undefined)
127
+ headers['Content-Type'] = 'application/json';
128
+ if (init.actingUser) {
129
+ const user = this.needUser(init.user);
130
+ // A person's own key (fsk_) already names the person; only an app key sends the header.
131
+ if (!key.startsWith('fsk_'))
132
+ headers['X-Harny-User'] = user;
133
+ }
134
+ const doFetch = this.options.fetch ?? globalThis.fetch;
135
+ const url = `${resolveBaseURL(this.options.baseURL)}${path}`;
136
+ let response;
137
+ try {
138
+ response = await doFetch(url, {
139
+ method,
140
+ headers,
141
+ body: init.body === undefined ? undefined : JSON.stringify(init.body),
142
+ });
143
+ }
144
+ catch (cause) {
145
+ throw new HarnyAPIError({
146
+ code: 'network-error',
147
+ status: 0,
148
+ debugMessage: cause instanceof Error ? cause.message : 'The request did not reach Harny.',
149
+ cause,
150
+ });
151
+ }
152
+ const requestId = response.headers.get('x-request-id') ?? undefined;
153
+ if (response.ok) {
154
+ if (response.status === 204)
155
+ return undefined;
156
+ const text = await response.text();
157
+ return (text ? JSON.parse(text) : undefined);
158
+ }
159
+ const retryHeader = response.headers.get('retry-after');
160
+ const retryAfter = retryHeader && /^\d+$/.test(retryHeader.trim()) ? Number(retryHeader) : undefined;
161
+ const text = await response.text().catch(() => '');
162
+ let parsed = {};
163
+ try {
164
+ parsed = text ? JSON.parse(text) : {};
165
+ }
166
+ catch {
167
+ parsed = {};
168
+ }
169
+ const code = typeof parsed.code === 'string' ? parsed.code : response.status === 429 ? 'rate-limited' : 'http-error';
170
+ const debugMessage = typeof parsed.debugMessage === 'string'
171
+ ? parsed.debugMessage
172
+ : response.status === 429
173
+ ? 'Too many requests this minute. Retry after the wait in retryAfter.'
174
+ : `Harny answered ${response.status}.`;
175
+ throw new HarnyAPIError({ code, status: response.status, debugMessage, data: parsed.data, retryAfter, requestId });
176
+ }
177
+ /** Send one data point. The same `id` with changed text replaces the old; the same text again is `unchanged`. */
178
+ async ingest(input) {
179
+ const body = dataPointBody(input);
180
+ if (input.idempotencyKey !== undefined)
181
+ body.idempotencyKey = input.idempotencyKey;
182
+ return this.request('POST', '/memory/ingest', { body, user: input.user, actingUser: true });
183
+ }
184
+ /** Send 1 to 1,000 data points. Retry with the same `idempotencyKey` to resume where it stopped. */
185
+ async ingestBatch(items, options = {}) {
186
+ if (!Array.isArray(items) || items.length < 1 || items.length > MAX_BATCH_ITEMS) {
187
+ throw new HarnyConfigError(`a batch holds 1 to ${MAX_BATCH_ITEMS} items`);
188
+ }
189
+ const seen = new Set();
190
+ const bodies = items.map((item, ordinal) => {
191
+ const body = dataPointBody(item);
192
+ if (typeof body.id === 'string') {
193
+ if (seen.has(body.id))
194
+ throw new HarnyConfigError(`item ${ordinal} repeats the id ${JSON.stringify(body.id)}`);
195
+ seen.add(body.id);
196
+ }
197
+ return body;
198
+ });
199
+ const body = { items: bodies };
200
+ if (options.idempotencyKey !== undefined)
201
+ body.idempotencyKey = options.idempotencyKey;
202
+ return this.request('POST', '/memory/ingest/batch', { body, user: options.user, actingUser: true });
203
+ }
204
+ async getIngestion(ingestionId, options = {}) {
205
+ if (!ingestionId)
206
+ throw new HarnyConfigError('ingestionId is required');
207
+ return this.request('GET', `/memory/ingest/${encodeURIComponent(ingestionId)}`, {
208
+ user: options.user,
209
+ actingUser: true,
210
+ });
211
+ }
212
+ /** Poll until the send is `completed` or `failed`. Throws a `timeout` HarnyAPIError after `timeoutMs`. */
213
+ async waitForIngestion(ingestionId, options = {}) {
214
+ const timeoutMs = options.timeoutMs ?? 120_000;
215
+ const pollMs = options.pollMs ?? 2_000;
216
+ const sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
217
+ const started = Date.now();
218
+ for (;;) {
219
+ const status = await this.getIngestion(ingestionId, { user: options.user });
220
+ if (status.status === 'completed' || status.status === 'failed')
221
+ return status;
222
+ if (Date.now() - started >= timeoutMs) {
223
+ throw new HarnyAPIError({
224
+ code: 'timeout',
225
+ status: 0,
226
+ debugMessage: `ingestion ${ingestionId} was still ${status.status} after ${timeoutMs / 1000}s`,
227
+ });
228
+ }
229
+ await sleep(pollMs);
230
+ }
231
+ }
232
+ /** Forget every data point of one send. Repeating the call is safe. */
233
+ async deleteIngestion(ingestionId, options = {}) {
234
+ if (!ingestionId)
235
+ throw new HarnyConfigError('ingestionId is required');
236
+ await this.request('DELETE', `/memory/ingest/${encodeURIComponent(ingestionId)}`, {
237
+ user: options.user,
238
+ actingUser: true,
239
+ });
240
+ }
241
+ /** Forget 1 to 1,000 data points by `sourceId`. If one id is unknown, none is deleted and the error names it. */
242
+ async deleteDataPoints(ids, options = {}) {
243
+ const unique = [...new Set(ids)];
244
+ if (unique.length < 1 || unique.length > 1000 || unique.some((id) => typeof id !== 'string' || !id.trim())) {
245
+ throw new HarnyConfigError('delete 1 to 1000 data points at a time, each id a non-blank string');
246
+ }
247
+ return this.request('POST', '/memory/data-points/delete', {
248
+ body: { ids: unique },
249
+ user: options.user,
250
+ actingUser: true,
251
+ });
252
+ }
253
+ /** Ranked, dated evidence for a question, as the named person. */
254
+ async recall(options) {
255
+ const identity = this.needUser(options.user);
256
+ return this.request('POST', '/memory/recall', {
257
+ body: recallBody(options, identity),
258
+ user: options.user,
259
+ actingUser: true,
260
+ });
261
+ }
262
+ /** This month's use of the app. Needs the app key. */
263
+ async usage() {
264
+ return this.request('GET', '/memory/usage');
265
+ }
266
+ }