@crewhaus/tool-result-store 0.7.0 → 0.8.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/NOTICE +9 -0
- package/README.md +11 -0
- package/dist/index.d.ts +35 -0
- package/dist/index.js +241 -19
- package/package.json +12 -7
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 [yyyy] [name of copyright owner]
|
|
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/NOTICE
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
CrewHaus Factory
|
|
2
|
+
Copyright 2026 Max Meier
|
|
3
|
+
|
|
4
|
+
This product includes software developed by Max Meier
|
|
5
|
+
(operating as StudioMax — https://studiomax.io) and contributors.
|
|
6
|
+
|
|
7
|
+
The CrewHaus name and logo are trademarks of Max Meier. See
|
|
8
|
+
https://github.com/crewhaus/factory/blob/main/TRADEMARK.md for the
|
|
9
|
+
use-of-marks policy.
|
package/README.md
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# @crewhaus/tool-result-store
|
|
2
|
+
|
|
3
|
+
Persist large tool results to disk and return a preview the model can re-read
|
|
4
|
+
|
|
5
|
+
Part of [CrewHaus](https://github.com/crewhaus/factory). Most people install the CLI (`npm install -g crewhaus`) rather than this package.
|
|
6
|
+
|
|
7
|
+
Which tools a spec can turn on, and how: [tools reference](https://github.com/crewhaus/docs/blob/main/TOOLS-REFERENCE.md).
|
|
8
|
+
|
|
9
|
+
Requires [Bun](https://bun.sh) `>=1.3.14`; plain Node is not supported.
|
|
10
|
+
|
|
11
|
+
[Source](https://github.com/crewhaus/factory/tree/main/packages/tool-result-store)
|
package/dist/index.d.ts
CHANGED
|
@@ -5,16 +5,44 @@ export type StoreOptions = {
|
|
|
5
5
|
readonly toolUseId: string;
|
|
6
6
|
readonly thresholdBytes?: number;
|
|
7
7
|
readonly previewLines?: number;
|
|
8
|
+
/**
|
|
9
|
+
* The most UTF-8 bytes of the result the preview carries, before the
|
|
10
|
+
* marker. Defaults to `thresholdBytes`, so a persisted result's preview is
|
|
11
|
+
* never larger than a result small enough to go through whole.
|
|
12
|
+
*/
|
|
13
|
+
readonly previewBytes?: number;
|
|
8
14
|
readonly rootDir?: string;
|
|
9
15
|
};
|
|
10
16
|
export type StoredResult = {
|
|
11
17
|
readonly previewContent: ToolExecuteResult;
|
|
12
18
|
readonly fullPath: string | null;
|
|
13
19
|
readonly persisted: boolean;
|
|
20
|
+
/**
|
|
21
|
+
* The full output was already on disk at `fullPath`, byte for byte (a
|
|
22
|
+
* retried call), and nothing was written this time.
|
|
23
|
+
*/
|
|
24
|
+
readonly reused?: boolean;
|
|
25
|
+
/**
|
|
26
|
+
* The result was over the threshold but could not be saved; the preview
|
|
27
|
+
* says so and `fullPath` is null. Why, naming the path tried.
|
|
28
|
+
*/
|
|
29
|
+
readonly unsaved?: string;
|
|
30
|
+
/**
|
|
31
|
+
* Where the rest of the output was saved in parts (part 2 onwards), each
|
|
32
|
+
* small enough for one `Read`; the preview names the first of them.
|
|
33
|
+
*/
|
|
34
|
+
readonly partPaths?: ReadonlyArray<string>;
|
|
14
35
|
};
|
|
15
36
|
export declare const DEFAULT_THRESHOLD_BYTES = 10240;
|
|
16
37
|
export declare const DEFAULT_PREVIEW_LINES = 100;
|
|
17
38
|
export declare const DEFAULT_ROOT_DIR = ".crewhaus/tool-results";
|
|
39
|
+
/**
|
|
40
|
+
* How many names (`<id>.txt`, then `<id>.2.txt` …) one result tries before
|
|
41
|
+
* it is reported unsaved. Each taken name costs one bounded compare-read.
|
|
42
|
+
*/
|
|
43
|
+
export declare const MAX_NAME_ATTEMPTS = 1000;
|
|
44
|
+
/** The most parts (the preview is part 1) a result is saved in for paging. */
|
|
45
|
+
export declare const MAX_PARTS = 64;
|
|
18
46
|
/**
|
|
19
47
|
* If `result.content` is at or under threshold, return it unchanged.
|
|
20
48
|
* Otherwise persist the full text under `<rootDir>/<runId>/<toolUseId>.txt`
|
|
@@ -23,6 +51,13 @@ export declare const DEFAULT_ROOT_DIR = ".crewhaus/tool-results";
|
|
|
23
51
|
* captured.
|
|
24
52
|
*/
|
|
25
53
|
export declare function storeAndPreview(result: ToolResult, opts: StoreOptions): Promise<StoredResult>;
|
|
54
|
+
/**
|
|
55
|
+
* The first `maxLines` lines of `content`, cut to at most `maxBytes` UTF-8
|
|
56
|
+
* bytes without splitting a character (flag-truth-6#4). Only the first
|
|
57
|
+
* `maxBytes` code units are ever looked at: every code unit is at least one
|
|
58
|
+
* byte, so nothing past them can fit.
|
|
59
|
+
*/
|
|
60
|
+
export declare function previewHead(content: string, maxLines: number, maxBytes: number): string;
|
|
26
61
|
/**
|
|
27
62
|
* Defence-in-depth boundary check: assert that a resolved absolute path lives
|
|
28
63
|
* strictly under `root`. Redundant with `rejectUnsafeSegment` on the normal
|
package/dist/index.js
CHANGED
|
@@ -8,11 +8,31 @@
|
|
|
8
8
|
* - Threshold: 10240 bytes (10 KB) of UTF-8.
|
|
9
9
|
* - Storage path: `<rootDir>/<runId>/<toolUseId>.txt`
|
|
10
10
|
* (rootDir defaults to `.crewhaus/tool-results` under cwd).
|
|
11
|
-
* - Preview: first 100 lines
|
|
11
|
+
* - Preview: the first 100 lines, cut to at most `previewBytes` bytes
|
|
12
|
+
* (default: the threshold) on a character boundary, then
|
|
13
|
+
* `[truncated, full output at <fullPath>]`. The byte cap matters for
|
|
14
|
+
* the common case of one long line — a JSON-encoded result — which the
|
|
15
|
+
* line limit alone passed through whole.
|
|
16
|
+
* - Parts: the rest of the output is also saved as
|
|
17
|
+
* `<toolUseId>.part-<k>.txt` files, each small enough to come back
|
|
18
|
+
* whole from one `Read`, each naming the next, and the preview names
|
|
19
|
+
* part 2. Without them the rest of a one-line result was out of reach:
|
|
20
|
+
* `Read` has no offset, and a `Read` of the full file is itself cut to
|
|
21
|
+
* the same preview. At most {@link MAX_PARTS} parts; past them the rest
|
|
22
|
+
* is only in the full file, and the last part says so.
|
|
12
23
|
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
24
|
+
* Exclusive writes: the file is created new (`O_EXCL`, via
|
|
25
|
+
* `@crewhaus/tool-safety/fs` `createExclusive`), so nothing is ever written
|
|
26
|
+
* through a link or over an existing file, and the directory it lands in
|
|
27
|
+
* must physically be inside `rootDir`. A `tool_use_id` is NOT unique within
|
|
28
|
+
* a run: providers that send no id get one synthesised per response
|
|
29
|
+
* (Gemini's `gemini_<name>_<n>`, an OpenAI-compatible server's
|
|
30
|
+
* `call_<n>`), so two calls can share one. When the name is taken, the file
|
|
31
|
+
* there is compared with this result: the same bytes (a retried call) reuse
|
|
32
|
+
* it; anything else — different output, a link, a FIFO — moves on to
|
|
33
|
+
* `<toolUseId>.<n>.txt`, and the preview's pointer names the file actually
|
|
34
|
+
* written. A result that cannot be saved at all still reaches the model as
|
|
35
|
+
* a preview, marked as cut short with the reason, instead of ending the run.
|
|
16
36
|
*
|
|
17
37
|
* Path traversal: `runId` and `toolUseId` are joined under `rootDir`
|
|
18
38
|
* after rejecting any value containing path separators or `..` to
|
|
@@ -23,10 +43,12 @@
|
|
|
23
43
|
* GrowthBook flag to override per tool. We collapse to a single global
|
|
24
44
|
* threshold and a plain-text marker.
|
|
25
45
|
*/
|
|
26
|
-
import {
|
|
27
|
-
import {
|
|
46
|
+
import { closeSync, writeSync } from "node:fs";
|
|
47
|
+
import { mkdir } from "node:fs/promises";
|
|
48
|
+
import { basename, join, resolve, sep } from "node:path";
|
|
28
49
|
import { RuntimeError } from "@crewhaus/errors";
|
|
29
50
|
import { assertSamePath, currentTenantContext, requireTenant } from "@crewhaus/tenancy";
|
|
51
|
+
import { createExclusive, openForRead, openForReadSync } from "@crewhaus/tool-safety/fs";
|
|
30
52
|
// When a tenant context is active, fail closed on a resolved storage path that
|
|
31
53
|
// escapes the tenant's toolResultRoot (CWE-1230). Outside a tenant scope (the
|
|
32
54
|
// common CLI case) this is a no-op so non-tenant behaviour is unchanged.
|
|
@@ -38,6 +60,15 @@ function fence(absPath) {
|
|
|
38
60
|
export const DEFAULT_THRESHOLD_BYTES = 10240;
|
|
39
61
|
export const DEFAULT_PREVIEW_LINES = 100;
|
|
40
62
|
export const DEFAULT_ROOT_DIR = ".crewhaus/tool-results";
|
|
63
|
+
/**
|
|
64
|
+
* How many names (`<id>.txt`, then `<id>.2.txt` …) one result tries before
|
|
65
|
+
* it is reported unsaved. Each taken name costs one bounded compare-read.
|
|
66
|
+
*/
|
|
67
|
+
export const MAX_NAME_ATTEMPTS = 1000;
|
|
68
|
+
/** The most parts (the preview is part 1) a result is saved in for paging. */
|
|
69
|
+
export const MAX_PARTS = 64;
|
|
70
|
+
/** No parts are written when the threshold leaves less than this for each. */
|
|
71
|
+
const MIN_PART_BYTES = 1024;
|
|
41
72
|
/**
|
|
42
73
|
* If `result.content` is at or under threshold, return it unchanged.
|
|
43
74
|
* Otherwise persist the full text under `<rootDir>/<runId>/<toolUseId>.txt`
|
|
@@ -48,6 +79,7 @@ export const DEFAULT_ROOT_DIR = ".crewhaus/tool-results";
|
|
|
48
79
|
export async function storeAndPreview(result, opts) {
|
|
49
80
|
const thresholdBytes = opts.thresholdBytes ?? DEFAULT_THRESHOLD_BYTES;
|
|
50
81
|
const previewLines = opts.previewLines ?? DEFAULT_PREVIEW_LINES;
|
|
82
|
+
const previewBytes = opts.previewBytes ?? thresholdBytes;
|
|
51
83
|
const rootDir = opts.rootDir ?? DEFAULT_ROOT_DIR;
|
|
52
84
|
// Section 14 — non-string content (image content arrays) bypasses
|
|
53
85
|
// persistence entirely. The blocks are forwarded as-is to the model so
|
|
@@ -62,23 +94,213 @@ export async function storeAndPreview(result, opts) {
|
|
|
62
94
|
}
|
|
63
95
|
rejectUnsafeSegment("runId", opts.runId);
|
|
64
96
|
rejectUnsafeSegment("toolUseId", opts.toolUseId);
|
|
65
|
-
const
|
|
66
|
-
fence(resolve(
|
|
67
|
-
await
|
|
97
|
+
const head = previewHead(result.content, previewLines, previewBytes);
|
|
98
|
+
fence(resolve(join(rootDir, opts.runId, `${opts.toolUseId}.txt`)));
|
|
99
|
+
const saved = await saveExclusive(rootDir, opts.runId, opts.toolUseId, result.content);
|
|
100
|
+
if (!saved.ok) {
|
|
101
|
+
return {
|
|
102
|
+
previewContent: `${head}\n[truncated; the full output could not be saved: ${saved.reason}]`,
|
|
103
|
+
fullPath: null,
|
|
104
|
+
persisted: false,
|
|
105
|
+
unsaved: saved.reason,
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
const parts = saveParts(rootDir, opts.runId, saved.fullPath, result.content, head, thresholdBytes);
|
|
109
|
+
const partLine = parts.kind === "saved"
|
|
110
|
+
? `\n[part 1 of ${parts.count}; Read ${parts.next} for part 2]`
|
|
111
|
+
: parts.kind === "failed"
|
|
112
|
+
? `\n[the rest could not also be saved in parts to Read one at a time: ${parts.reason}]`
|
|
113
|
+
: "";
|
|
114
|
+
const previewContent = `${head}${partLine}\n[truncated, full output at ${saved.fullPath}]`;
|
|
115
|
+
return {
|
|
116
|
+
previewContent,
|
|
117
|
+
fullPath: saved.fullPath,
|
|
118
|
+
persisted: true,
|
|
119
|
+
...(saved.reused ? { reused: true } : {}),
|
|
120
|
+
...(parts.kind === "saved" ? { partPaths: parts.paths } : {}),
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Save what the preview left out as parts 2…n beside the full output
|
|
125
|
+
* (`<name>.part-<k>.txt`), each at most `thresholdBytes` with its marker so
|
|
126
|
+
* one `Read` returns it whole. A part is cut on a character boundary, at a
|
|
127
|
+
* newline when one falls in its second half. Each part's marker names the
|
|
128
|
+
* next; the last says it is the end, or that the rest is only in the full
|
|
129
|
+
* output when {@link MAX_PARTS} ran out. Written exclusively like the full
|
|
130
|
+
* output: a part already there with the same bytes (a retried call) is
|
|
131
|
+
* reused, anything else stops the parts.
|
|
132
|
+
*/
|
|
133
|
+
function saveParts(rootDir, runId, fullPath, content, head, thresholdBytes) {
|
|
134
|
+
const bytes = Buffer.from(content, "utf8");
|
|
135
|
+
const start = Buffer.byteLength(head, "utf8");
|
|
136
|
+
if (start >= bytes.length)
|
|
137
|
+
return { kind: "none" };
|
|
138
|
+
// Room for the marker: two paths and the words around them.
|
|
139
|
+
const partBytes = Math.floor(thresholdBytes) - (2 * Buffer.byteLength(fullPath, "utf8") + 160);
|
|
140
|
+
if (!(partBytes >= MIN_PART_BYTES))
|
|
141
|
+
return { kind: "none" };
|
|
142
|
+
const slices = [];
|
|
143
|
+
let at = start;
|
|
144
|
+
while (at < bytes.length && slices.length < MAX_PARTS - 1) {
|
|
145
|
+
let end = Math.min(at + partBytes, bytes.length);
|
|
146
|
+
if (end < bytes.length) {
|
|
147
|
+
const newline = bytes.lastIndexOf(0x0a, end - 1);
|
|
148
|
+
if (newline >= at + partBytes / 2)
|
|
149
|
+
end = newline + 1;
|
|
150
|
+
else
|
|
151
|
+
while (end > at && ((bytes[end] ?? 0) & 0xc0) === 0x80)
|
|
152
|
+
end--;
|
|
153
|
+
}
|
|
154
|
+
if (end <= at)
|
|
155
|
+
break;
|
|
156
|
+
slices.push([at, end]);
|
|
157
|
+
at = end;
|
|
158
|
+
}
|
|
159
|
+
const remaining = bytes.length - at;
|
|
160
|
+
const stem = basename(fullPath).replace(/\.txt$/, "");
|
|
161
|
+
const count = slices.length + 1;
|
|
162
|
+
const nameOf = (k) => `${stem}.part-${k}.txt`;
|
|
163
|
+
const pathOf = (k) => join(rootDir, runId, nameOf(k));
|
|
164
|
+
const paths = [];
|
|
165
|
+
for (let i = 0; i < slices.length; i++) {
|
|
166
|
+
const k = i + 2;
|
|
167
|
+
const [from, to] = slices[i];
|
|
168
|
+
const marker = k < count
|
|
169
|
+
? `[part ${k} of ${count}; Read ${pathOf(k + 1)} for part ${k + 1}; full output at ${fullPath}]`
|
|
170
|
+
: remaining > 0
|
|
171
|
+
? `[part ${k} of ${count}, the last part saved; the remaining ${remaining} bytes are only in the full output at ${fullPath}]`
|
|
172
|
+
: `[part ${k} of ${count}, the end of the output; full output at ${fullPath}]`;
|
|
173
|
+
const part = Buffer.concat([bytes.subarray(from, to), Buffer.from(`\n${marker}`, "utf8")]);
|
|
174
|
+
const written = writeOrReuse(rootDir, `${runId}/${nameOf(k)}`, pathOf(k), part);
|
|
175
|
+
if (!written.ok)
|
|
176
|
+
return { kind: "failed", reason: written.reason };
|
|
177
|
+
paths.push(pathOf(k));
|
|
178
|
+
}
|
|
179
|
+
return { kind: "saved", count, next: pathOf(2), paths };
|
|
180
|
+
}
|
|
181
|
+
/** Create `rel` under `rootDir` holding `bytes`, or accept it when it already holds them. */
|
|
182
|
+
function writeOrReuse(rootDir, rel, shownPath, bytes) {
|
|
183
|
+
fence(resolve(shownPath));
|
|
184
|
+
const created = createExclusive(rootDir, rel, { createParents: true });
|
|
185
|
+
if (created.ok) {
|
|
186
|
+
try {
|
|
187
|
+
let off = 0;
|
|
188
|
+
while (off < bytes.length)
|
|
189
|
+
off += writeSync(created.fd, bytes, off, bytes.length - off);
|
|
190
|
+
return { ok: true };
|
|
191
|
+
}
|
|
192
|
+
catch (err) {
|
|
193
|
+
return { ok: false, reason: `${shownPath} could not be written (${err.message})` };
|
|
194
|
+
}
|
|
195
|
+
finally {
|
|
196
|
+
closeSync(created.fd);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
if (created.code !== "exists")
|
|
200
|
+
return { ok: false, reason: created.reason };
|
|
201
|
+
const existing = openForReadSync(rootDir, rel, {
|
|
202
|
+
maxBytes: bytes.length,
|
|
203
|
+
followLeafSymlink: false,
|
|
204
|
+
});
|
|
205
|
+
return existing.ok && !existing.truncated && Buffer.from(existing.bytes).equals(bytes)
|
|
206
|
+
? { ok: true }
|
|
207
|
+
: { ok: false, reason: `${shownPath} is taken by other content` };
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* Write `content` to a NEW file under `<rootDir>/<runId>/`, first as
|
|
211
|
+
* `<toolUseId>.txt`, then `<toolUseId>.<n>.txt` while the name is taken by
|
|
212
|
+
* anything that is not these exact bytes. Never writes through a link, over
|
|
213
|
+
* an existing file, or outside `rootDir`.
|
|
214
|
+
*/
|
|
215
|
+
async function saveExclusive(rootDir, runId, toolUseId, content) {
|
|
216
|
+
const bytes = Buffer.from(content, "utf8");
|
|
68
217
|
try {
|
|
69
|
-
|
|
218
|
+
// The root is the runtime's own directory, never a model-named path.
|
|
219
|
+
await mkdir(rootDir, { recursive: true });
|
|
70
220
|
}
|
|
71
221
|
catch (err) {
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
222
|
+
return { ok: false, reason: `${rootDir} could not be created (${err.message})` };
|
|
223
|
+
}
|
|
224
|
+
for (let n = 1; n <= MAX_NAME_ATTEMPTS; n++) {
|
|
225
|
+
const name = n === 1 ? `${toolUseId}.txt` : `${toolUseId}.${n}.txt`;
|
|
226
|
+
const rel = `${runId}/${name}`;
|
|
227
|
+
const fullPath = join(rootDir, runId, name);
|
|
228
|
+
fence(resolve(fullPath));
|
|
229
|
+
const created = createExclusive(rootDir, rel, { createParents: true });
|
|
230
|
+
if (created.ok) {
|
|
231
|
+
try {
|
|
232
|
+
let off = 0;
|
|
233
|
+
while (off < bytes.length)
|
|
234
|
+
off += writeSync(created.fd, bytes, off, bytes.length - off);
|
|
235
|
+
}
|
|
236
|
+
catch (err) {
|
|
237
|
+
return {
|
|
238
|
+
ok: false,
|
|
239
|
+
reason: `${fullPath} could not be written (${err.message})`,
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
finally {
|
|
243
|
+
closeSync(created.fd);
|
|
244
|
+
}
|
|
245
|
+
return { ok: true, fullPath, reused: false };
|
|
246
|
+
}
|
|
247
|
+
// A link or a special file at the name is not this result: try the next
|
|
248
|
+
// name, without opening it. Any other refusal (the run directory linked
|
|
249
|
+
// out of the root, no permission) would refuse every name alike.
|
|
250
|
+
if (created.code === "is-symlink" || created.code === "not-regular-file")
|
|
251
|
+
continue;
|
|
252
|
+
if (created.code !== "exists")
|
|
253
|
+
return { ok: false, reason: created.reason };
|
|
254
|
+
// A regular file is there. The same bytes are a retried call: reuse
|
|
255
|
+
// them. Anything else is another call's output under a repeated id.
|
|
256
|
+
const existing = await openForRead(rootDir, rel, {
|
|
257
|
+
maxBytes: bytes.length,
|
|
258
|
+
followLeafSymlink: false,
|
|
259
|
+
});
|
|
260
|
+
if (existing.ok && !existing.truncated && Buffer.from(existing.bytes).equals(bytes)) {
|
|
261
|
+
return { ok: true, fullPath, reused: true };
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
return {
|
|
265
|
+
ok: false,
|
|
266
|
+
reason: `every name from ${join(rootDir, runId, `${toolUseId}.txt`)} to ${toolUseId}.${MAX_NAME_ATTEMPTS}.txt is taken`,
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
/**
|
|
270
|
+
* The first `maxLines` lines of `content`, cut to at most `maxBytes` UTF-8
|
|
271
|
+
* bytes without splitting a character (flag-truth-6#4). Only the first
|
|
272
|
+
* `maxBytes` code units are ever looked at: every code unit is at least one
|
|
273
|
+
* byte, so nothing past them can fit.
|
|
274
|
+
*/
|
|
275
|
+
export function previewHead(content, maxLines, maxBytes) {
|
|
276
|
+
const lines = Math.floor(maxLines);
|
|
277
|
+
const bytes = Math.floor(maxBytes);
|
|
278
|
+
if (!(lines > 0) || !(bytes > 0))
|
|
279
|
+
return "";
|
|
280
|
+
const scan = content.length > bytes ? content.slice(0, bytes) : content;
|
|
281
|
+
let end = scan.length;
|
|
282
|
+
let from = 0;
|
|
283
|
+
for (let n = 0; n < lines; n++) {
|
|
284
|
+
const newline = scan.indexOf("\n", from);
|
|
285
|
+
if (newline === -1)
|
|
286
|
+
break;
|
|
287
|
+
if (n === lines - 1) {
|
|
288
|
+
end = newline;
|
|
289
|
+
break;
|
|
290
|
+
}
|
|
291
|
+
from = newline + 1;
|
|
77
292
|
}
|
|
78
|
-
const
|
|
79
|
-
const
|
|
80
|
-
|
|
81
|
-
|
|
293
|
+
const head = scan.slice(0, end);
|
|
294
|
+
const encoded = Buffer.from(head, "utf8");
|
|
295
|
+
if (encoded.length <= bytes)
|
|
296
|
+
return head;
|
|
297
|
+
// Step back over continuation bytes (10xxxxxx) to the start of a character.
|
|
298
|
+
// A surrogate pair the window split in two encodes as a replacement
|
|
299
|
+
// character that starts at or past byte `bytes - 1`, so this drops it too.
|
|
300
|
+
let cut = bytes;
|
|
301
|
+
while (cut > 0 && ((encoded[cut] ?? 0) & 0xc0) === 0x80)
|
|
302
|
+
cut--;
|
|
303
|
+
return encoded.subarray(0, cut).toString("utf8");
|
|
82
304
|
}
|
|
83
305
|
function rejectUnsafeSegment(label, value) {
|
|
84
306
|
if (value === "" ||
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@crewhaus/tool-result-store",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Persist large tool results to disk and return a preview the model can re-read",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -8,17 +8,19 @@
|
|
|
8
8
|
"exports": {
|
|
9
9
|
".": {
|
|
10
10
|
"types": "./dist/index.d.ts",
|
|
11
|
-
"import": "./dist/index.js"
|
|
11
|
+
"import": "./dist/index.js",
|
|
12
|
+
"default": "./dist/index.js"
|
|
12
13
|
}
|
|
13
14
|
},
|
|
14
15
|
"scripts": {
|
|
15
16
|
"test": "bun test src"
|
|
16
17
|
},
|
|
17
18
|
"dependencies": {
|
|
18
|
-
"@crewhaus/errors": "0.
|
|
19
|
-
"@crewhaus/tenancy": "0.
|
|
20
|
-
"@crewhaus/tool-catalog": "0.
|
|
21
|
-
"@crewhaus/tool-executor": "0.
|
|
19
|
+
"@crewhaus/errors": "0.8.0",
|
|
20
|
+
"@crewhaus/tenancy": "0.8.0",
|
|
21
|
+
"@crewhaus/tool-catalog": "0.8.0",
|
|
22
|
+
"@crewhaus/tool-executor": "0.8.0",
|
|
23
|
+
"@crewhaus/tool-safety": "0.8.0"
|
|
22
24
|
},
|
|
23
25
|
"license": "Apache-2.0",
|
|
24
26
|
"author": {
|
|
@@ -38,5 +40,8 @@
|
|
|
38
40
|
"publishConfig": {
|
|
39
41
|
"access": "public"
|
|
40
42
|
},
|
|
41
|
-
"files": ["dist", "README.md", "LICENSE", "NOTICE"]
|
|
43
|
+
"files": ["dist", "README.md", "LICENSE", "NOTICE"],
|
|
44
|
+
"engines": {
|
|
45
|
+
"bun": ">=1.3.14"
|
|
46
|
+
}
|
|
42
47
|
}
|