@yaks/context 0.0.0-stage → 0.2.36

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/result.ts ADDED
@@ -0,0 +1,321 @@
1
+ /** Small model-facing descriptions of JSON values kept whole in the graph. */
2
+ import {
3
+ LexError,
4
+ parse,
5
+ ParseError,
6
+ run,
7
+ RuntimeError,
8
+ type Value,
9
+ } from '@gabrielbryk/jq-ts'
10
+
11
+ export let RESULT_LIMIT: number = 16_384
12
+ export let RESULT_MAX: number = 33_554_432
13
+
14
+ let BAD_ESCAPE = /^Invalid escape sequence "(\\[\s\S])"$/
15
+ let LIMITS = { maxSteps: 1_000_000, maxDepth: 128 }
16
+
17
+ /** Regex escaping as it appears in a result_query JSON argument. */
18
+ export let jqRegex: string =
19
+ 'For a literal question mark or dot in a regex, use test("[?]") or test("[.]").'
20
+
21
+ let object = (value: unknown): value is Record<string, unknown> =>
22
+ !!value && typeof value == 'object' && !Array.isArray(value)
23
+ let names = (value: Record<string, unknown>) =>
24
+ Object.keys(value).slice(0, 16).map((key) => key.slice(0, 48))
25
+ let typeOf = (value: unknown) =>
26
+ value === null ? 'null' : Array.isArray(value) ? 'array' : typeof value
27
+ let withArticle = (type: string) =>
28
+ (type == 'array' || type == 'object' || type == 'undefined' ? 'an ' : 'a ') +
29
+ type
30
+ let root = (value: unknown) => {
31
+ let type = withArticle(typeOf(value))
32
+ if (object(value)) return type + ' with keys ' + JSON.stringify(names(value))
33
+ if (Array.isArray(value)) return type + ' of length ' + value.length
34
+ return type
35
+ }
36
+
37
+ // The lexer ends its span just after the bad escape. Repair that one string
38
+ // at a time so comments, interpolation, and existing escapes keep their text.
39
+ let escaped = (filter: string, error: unknown) => {
40
+ for (let i = 0; i < 16; i++) {
41
+ if (!(error instanceof LexError)) return
42
+ let escape = error.message.match(BAD_ESCAPE)?.[1]
43
+ let at = error.span.end - 2
44
+ if (!escape || filter.slice(at, at + 2) != escape) return
45
+ filter = filter.slice(0, at) + '\\' + filter.slice(at)
46
+ try {
47
+ parse(filter)
48
+ return filter
49
+ } catch (next) {
50
+ error = next
51
+ }
52
+ }
53
+ }
54
+
55
+ let nullOperand = (filter: string, error: RuntimeError) => {
56
+ let left = /^Cannot subtract \w+ from null$/.test(error.message)
57
+ let right = /^Cannot subtract null from \w+$/.test(error.message)
58
+ if (!left && !right) return
59
+ let expr = filter.slice(error.span.start, error.span.end)
60
+ try {
61
+ let node = parse(expr)
62
+ if (node.kind != 'Binary' || node.op != '-') return
63
+ let { start, end } = (left ? node.left : node.right).span
64
+ return expr.slice(start, end)
65
+ } catch {
66
+ // A span in a compound assignment may name the assignment itself.
67
+ }
68
+ }
69
+
70
+ // Follow the slice's input. An as-binding passes its original input to
71
+ // the body and can supply variables used by the slice's bounds.
72
+ let slicePath = (filter: string, { start, end }: RuntimeError['span']) => {
73
+ let node = parse(filter)
74
+ let path = []
75
+ while (node.kind == 'Pipe' || node.kind == 'As') {
76
+ if (node.kind == 'As') {
77
+ node = end <= node.bind.span.end ? node.bind : node.body
78
+ } else if (end <= node.left.span.end) {
79
+ node = node.left
80
+ } else {
81
+ path.push(filter.slice(node.left.span.start, node.left.span.end))
82
+ node = node.right
83
+ }
84
+ }
85
+ if (
86
+ node.kind != 'Slice' || node.span.start != start || node.span.end != end
87
+ ) {
88
+ return
89
+ }
90
+ let target = filter.slice(node.target.span.start, node.target.span.end)
91
+ let atRoot = target == '.' && !path.length
92
+ if (target != '.' || atRoot) path.push(target)
93
+ return { path: path.join(' | '), root: atRoot ? node.target.span : null }
94
+ }
95
+
96
+ let sliceHint = (filter: string, value: Value, error: RuntimeError) => {
97
+ if (error.message != 'Slice expected string or array') return ''
98
+ try {
99
+ let source = slicePath(filter, error.span)
100
+ if (source) {
101
+ let { path, root: target } = source
102
+ let table = target && object(value) && rows(value)
103
+ if (target && table) {
104
+ let { start, end } = target
105
+ let query = filter.slice(0, start) + table.path + filter.slice(end)
106
+ return ` Slice target . has type object. Slice the rows at ${table.path}: ` +
107
+ 'retry with the same id and ' + JSON.stringify({ query }) + '.'
108
+ }
109
+ let [type] = run(
110
+ 'first((' + path + ') | type | select(. != "array" and . != "string"))',
111
+ value,
112
+ { limits: { ...LIMITS, maxOutputs: RESULT_MAX } },
113
+ )
114
+ if (typeof type == 'string') {
115
+ let next = type == 'object' ? path + ' | keys' : path
116
+ return ' Slice target ' + path + ' has type ' + type + '. ' +
117
+ (type == 'object'
118
+ ? 'To list its keys, '
119
+ : 'To read that value without slicing, ') +
120
+ 'retry with the same id and ' + JSON.stringify({ query: next }) + '.'
121
+ }
122
+ }
123
+ } catch {
124
+ // The diagnostic is bounded by the same evaluation limits.
125
+ }
126
+ let { start, end } = error.span
127
+ return ' Failing slice: ' + filter.slice(start, end) + '.'
128
+ }
129
+
130
+ let caseHint = (value: Value, error: RuntimeError) => {
131
+ if (!/^ascii_(?:down|up)case expects string$/.test(error.message)) return ''
132
+ let [fn] = error.message.split(' ')
133
+ let table = rows(value)
134
+ let example = table
135
+ ? `${table.path}[] | .. | strings | ${fn}`
136
+ : `.. | strings | ${fn}`
137
+ return ` Select a string field before ${fn}. To change case of all strings in ${
138
+ table ? 'the result rows' : 'the input'
139
+ }, retry with the same id and ${JSON.stringify({ query: example })}.`
140
+ }
141
+
142
+ let jqFailure = (error: Error, filter: string, value: Value): Error => {
143
+ if (
144
+ error instanceof ParseError || error instanceof LexError &&
145
+ !BAD_ESCAPE.test(error.message)
146
+ ) {
147
+ let before = filter.slice(0, error.span.start).split('\n')
148
+ let path = rows(value)?.path
149
+ let query = path ? `${path}[:3]` : '.'
150
+ return new Error(
151
+ `jq syntax error at line ${before.length}, column ${
152
+ before.at(-1)!.length + 1
153
+ }: ` +
154
+ `${error.message}. ` +
155
+ (error.message == 'Unterminated string literal'
156
+ ? 'Close the string with a double quote. '
157
+ : '') +
158
+ `Try ${JSON.stringify({ query })}. Input root is ${root(value)}.`,
159
+ )
160
+ }
161
+ let said = 'jq query failed: ' + error.message + '. Input root is ' +
162
+ root(value) + '.'
163
+ if (error instanceof LexError && BAD_ESCAPE.test(error.message)) {
164
+ return new Error(said + ' ' + jqRegex)
165
+ }
166
+ let operand = error instanceof RuntimeError && nullOperand(filter, error)
167
+ return new Error(
168
+ operand
169
+ ? said + ' The operand ' + operand + ' evaluated to null. ' +
170
+ 'If missing should count as zero, use (' + operand +
171
+ ' // 0) in the subtraction.'
172
+ : said +
173
+ (error instanceof RuntimeError
174
+ ? sliceHint(filter, value, error) + caseHint(value, error)
175
+ : ''),
176
+ )
177
+ }
178
+
179
+ /**
180
+ * The values a jq filter makes of a kept result, with bounded work even for
181
+ * a recursive filter. Preserve backslashes in escapes jq does not recognize,
182
+ * so regex escapes can be entered directly. Refusals describe the root and
183
+ * can point to an offending expression or give a query the caller can retry.
184
+ *
185
+ * ```ts
186
+ * import { equal } from '@yaks/testing'
187
+ * equal(jqOver('.a', { a: 1 }), [1])
188
+ * ```
189
+ */
190
+ export let jqOver = (
191
+ filter: string,
192
+ value: unknown,
193
+ outputs = RESULT_MAX,
194
+ ): unknown[] => {
195
+ let options = { limits: { ...LIMITS, maxOutputs: outputs } }
196
+ try {
197
+ return run(filter, value as Value, options)
198
+ } catch (error) {
199
+ let fixed = escaped(filter, error)
200
+ if (!fixed) throw jqFailure(error as Error, filter, value as Value)
201
+ try {
202
+ return run(fixed, value as Value, options)
203
+ } catch (error) {
204
+ throw jqFailure(error as Error, fixed, value as Value)
205
+ }
206
+ }
207
+ }
208
+ export let resultBytes = (value: unknown): number =>
209
+ new TextEncoder().encode(JSON.stringify(value) ?? 'null').length
210
+
211
+ let rows = (
212
+ value: unknown,
213
+ path = '.',
214
+ depth = 0,
215
+ ): { value: unknown[]; path: string } | undefined => {
216
+ if (Array.isArray(value)) return { value, path }
217
+ if (!object(value)) return
218
+ for (let key of ['result', 'rows', 'data', 'values']) {
219
+ if (Array.isArray(value[key])) {
220
+ return {
221
+ value: value[key],
222
+ path: path == '.' ? '.' + key : path + '.' + key,
223
+ }
224
+ }
225
+ }
226
+ if (depth >= 4) return
227
+ for (let key of ['structuredContent', 'value']) {
228
+ let table = rows(
229
+ value[key],
230
+ path == '.' ? '.' + key : path + '.' + key,
231
+ depth + 1,
232
+ )
233
+ if (table) return table
234
+ }
235
+ }
236
+ type Shape = {
237
+ type: string
238
+ keys?: string[]
239
+ characters?: number
240
+ rows?: number
241
+ path?: string
242
+ columns?: string[]
243
+ }
244
+ let shape = (value: unknown): Shape => {
245
+ let table = rows(value)
246
+ return {
247
+ type: typeOf(value),
248
+ ...object(value) ? { keys: names(value) } : {},
249
+ ...typeof value == 'string' ? { characters: value.length } : {},
250
+ ...table
251
+ ? {
252
+ rows: table.value.length,
253
+ path: table.path,
254
+ columns: [
255
+ ...new Set(
256
+ table.value.slice(0, 3).flatMap((row) =>
257
+ object(row) ? names(row) : []
258
+ ),
259
+ ),
260
+ ].slice(0, 16),
261
+ }
262
+ : {},
263
+ }
264
+ }
265
+ let sample = (value: unknown, depth = 0): unknown => {
266
+ if (typeof value == 'string') {
267
+ return value.length > 256 ? value.slice(0, 256) + '…' : value
268
+ }
269
+ if (depth >= 4 && value && typeof value == 'object') return '[…]'
270
+ if (Array.isArray(value)) {
271
+ return value.slice(0, 3).map((v) => sample(v, depth + 1))
272
+ }
273
+ if (!object(value)) return value
274
+ return Object.fromEntries(
275
+ Object.entries(value).slice(0, 8).map(([k, v]) => [
276
+ k.slice(0, 80),
277
+ sample(v, depth + 1),
278
+ ]),
279
+ )
280
+ }
281
+ let preview = (value: unknown) => {
282
+ let out = sample(value)
283
+ let text = JSON.stringify(out) ?? 'null'
284
+ return resultBytes(out) > 4096 ? text.slice(0, 1000) + '…' : out
285
+ }
286
+
287
+ export type ResultSummary = {
288
+ id: string
289
+ bytes: number
290
+ shape: ReturnType<typeof shape>
291
+ preview: unknown
292
+ message: string
293
+ }
294
+ export let resultSummary = (
295
+ id: string,
296
+ value: unknown,
297
+ bytes: number = resultBytes(value),
298
+ ): ResultSummary => ({
299
+ id,
300
+ bytes,
301
+ shape: shape(value),
302
+ preview: preview(value),
303
+ message: 'The complete result is kept in this space’s graph. ' +
304
+ 'Use result_query({id, query}) with jq syntax to narrow it, or ' +
305
+ 'await results.read(id) inside code_mode. The preview is abbreviated.',
306
+ })
307
+
308
+ export let RESULT_SCHEMA: Record<string, unknown> = {
309
+ type: 'object',
310
+ properties: {
311
+ id: { type: 'string' },
312
+ bytes: { type: 'number' },
313
+ shape: { type: 'object' },
314
+ preview: {},
315
+ message: { type: 'string' },
316
+ space: { type: 'string' },
317
+ app: { type: 'string' },
318
+ scope: { type: 'string' },
319
+ },
320
+ required: ['id', 'bytes', 'shape', 'preview', 'message'],
321
+ }
package/vocab.js ADDED
@@ -0,0 +1,16 @@
1
+ // The component declarations, and nothing else: the module a server or a
2
+ // browser page imports at `@yaks/context/vocab`. It reaches no storage, no SQL
3
+ // and no runtime.
4
+ import doc from './vocab.json' with {
5
+ type: 'json'
6
+ };
7
+ import manifest from './package.json' with {
8
+ type: 'json'
9
+ };
10
+ /** The `prompt` entry's vocabulary, in the form `loadVocab` accepts. */ export let contextDoc = doc;
11
+ /** What this package is: its manifest's description, the one place it is
12
+ * written, which a host stamps on each document here. */ export let description = manifest.description;
13
+ /** Every document this plugin declares. */ export let docs = [
14
+ contextDoc
15
+ ];
16
+ //# sourceMappingURL=vocab.js.map
package/vocab.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vocab.js","sources":["./vocab.ts"],"names":[],"mappings":"AAAA,yEAAyE;AACzE,+EAA+E;AAC/E,kBAAkB;AAGlB,OAAO,SAAS,oBAAoB;EAAE,MAAM;AAAO,EAAC;AACpD,OAAO,cAAc,sBAAsB;EAAE,MAAM;AAAO,EAAC;AAE3D,sEAAsE,GACtE,OAAO,IAAI,aAAuB,IAAG;AAErC;uDACuD,GACvD,OAAO,IAAI,cAAsB,SAAS,WAAW,CAAA;AAErD,yCAAyC,GACzC,OAAO,IAAI,OAAmB;EAAC;CAAW,CAAA"}
package/vocab.json ADDED
@@ -0,0 +1,57 @@
1
+ {
2
+ "$id": "urn:uuid:5cd6899e-e264-46b7-8e72-d76afb2e2bf9",
3
+ "title": "context",
4
+ "$defs": {
5
+ "prompt": {
6
+ "$id": "urn:uuid:8d8f2b82-81e3-4b1d-9fb4-bba7f2fa9896",
7
+ "component": true,
8
+ "journal": false,
9
+ "type": "object",
10
+ "description": "Explicitly admitted instruction snapshot; never inferred from file reads or tool output. Content carries the exact text.",
11
+ "properties": {
12
+ "scope": {
13
+ "$id": "urn:uuid:fae8f2ee-0638-4e0d-b8ab-add00002f6dc",
14
+ "type": "string",
15
+ "description": "shared instructions copied to fresh children, local instructions for this transcript, recap placed before its conversation history, or turn: a note held for its turn alone, which a checkpoint drops"
16
+ },
17
+ "source": {
18
+ "$id": "urn:uuid:94148668-84c2-4d22-8ed3-8c11b8a56707",
19
+ "type": "string",
20
+ "description": "Source label or canonical file path; descriptive, not reread at delivery"
21
+ },
22
+ "revision": {
23
+ "$id": "urn:uuid:4affcffe-9790-4fa5-8a0a-1b33d0599381",
24
+ "type": "string",
25
+ "description": "SHA-256 of the admitted text when loaded from a file"
26
+ }
27
+ }
28
+ },
29
+ "context_output": {
30
+ "$id": "urn:uuid:6d2fb192-d17b-42c3-b85a-d55afc7aac89",
31
+ "component": true,
32
+ "journal": false,
33
+ "type": "object",
34
+ "description": "Immutable full tool-result snapshot, scoped by originating transcript entry.",
35
+ "properties": {
36
+ "source": {
37
+ "$id": "urn:uuid:5e898bf3-058b-4c18-b79d-84444b1bdb15",
38
+ "type": "string"
39
+ },
40
+ "revision": {
41
+ "$id": "urn:uuid:72b09c0a-4d9a-4e2b-8da1-42a8d70c8036",
42
+ "type": "string"
43
+ },
44
+ "body": {
45
+ "$id": "urn:uuid:823a457d-ea97-4ee9-aa3f-8996237c1d34",
46
+ "type": "string",
47
+ "store": "blob"
48
+ },
49
+ "reader": {
50
+ "$id": "urn:uuid:d7221cfc-c9b4-4d29-9ce4-440f89f53d22",
51
+ "type": "string",
52
+ "description": "Caller principal permitted to inspect a snapshot kept by a multi-user host; omitted when the graph itself provides its access boundary."
53
+ }
54
+ }
55
+ }
56
+ }
57
+ }
package/vocab.ts ADDED
@@ -0,0 +1,17 @@
1
+ // The component declarations, and nothing else: the module a server or a
2
+ // browser page imports at `@yaks/context/vocab`. It reaches no storage, no SQL
3
+ // and no runtime.
4
+
5
+ import type { VocabDoc } from 'jsr:@yaks/vocab@0.2.36'
6
+ import doc from './vocab.json' with { type: 'json' }
7
+ import manifest from './package.json' with { type: 'json' }
8
+
9
+ /** The `prompt` entry's vocabulary, in the form `loadVocab` accepts. */
10
+ export let contextDoc: VocabDoc = doc
11
+
12
+ /** What this package is: its manifest's description, the one place it is
13
+ * written, which a host stamps on each document here. */
14
+ export let description: string = manifest.description
15
+
16
+ /** Every document this plugin declares. */
17
+ export let docs: VocabDoc[] = [contextDoc]