@pulsarinteractive/geniustasker 0.1.0-beta.17 → 0.1.0-beta.18

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.
@@ -0,0 +1,221 @@
1
+ import * as z from 'zod/v4';
2
+ import tools from '../remote/tool-catalog.json' with { type: 'json' };
3
+ import { fail } from './errors.mjs';
4
+
5
+ export const memoryReadPagesTool = tools.find((tool) => tool.name === 'tasker_memory_read_pages');
6
+ export const memoryReadPagesSchema = z.fromJSONSchema(memoryReadPagesTool.inputSchema);
7
+ const encoder = new TextEncoder();
8
+ const byteLength = (value) => encoder.encode(JSON.stringify(value)).length;
9
+ const batchBytes = 64 * 1024;
10
+ const revisionPattern = /^(0|[1-9][0-9]{0,31})$/;
11
+ const sectionResult = z.object({
12
+ scope: z.string(),
13
+ id: z.string(),
14
+ title: z.string().max(160),
15
+ revision: z.string(),
16
+ epoch: z.string().min(1).max(128),
17
+ checkpoint: z.string(),
18
+ accessRevision: z.string().min(1).max(256),
19
+ mode: z.enum(['blocks', 'outline']),
20
+ notModified: z.boolean(),
21
+ nextCursor: z.string().min(1).max(2048).nullable(),
22
+ items: z
23
+ .array(
24
+ z.object({
25
+ id: z.string().regex(/^[a-zA-Z0-9_-]{1,80}$/),
26
+ kind: z.enum(['markdown', 'image', 'attachment', 'code', 'callout', 'mermaid']),
27
+ order: z.number().int(),
28
+ text: z.string().optional(),
29
+ offset: z.number().int().nonnegative().optional(),
30
+ complete: z.boolean().optional(),
31
+ assetId: z.string().max(128).nullish(),
32
+ caption: z.string().max(1000).nullish(),
33
+ alt: z.string().max(1000).nullish(),
34
+ language: z.string().max(40).nullish(),
35
+ }),
36
+ )
37
+ .max(64),
38
+ });
39
+
40
+ function validateRequest(input) {
41
+ const parsed = memoryReadPagesSchema.safeParse(input);
42
+ if (!parsed.success) {
43
+ fail('invalid_arguments', 'Choose one to five pages in one Memory.');
44
+ }
45
+ const { pages, epoch, checkpoint } = parsed.data;
46
+ if (
47
+ new Set(pages.map((page) => page.pageId)).size !== pages.length ||
48
+ (epoch === undefined) !== (checkpoint === undefined) ||
49
+ pages.some(
50
+ (page) =>
51
+ (page.blockIds &&
52
+ (page.mode !== 'blocks' || new Set(page.blockIds).size !== page.blockIds.length)) ||
53
+ (page.cursor && (!epoch || !page.revision || page.knownRevision !== undefined)) ||
54
+ (page.revision !== undefined &&
55
+ page.knownRevision !== undefined &&
56
+ page.revision !== page.knownRevision),
57
+ )
58
+ ) {
59
+ fail(
60
+ 'invalid_arguments',
61
+ 'Use different page IDs. Continue the same block selection with its cursor, revision, epoch and checkpoint.',
62
+ );
63
+ }
64
+ return parsed.data;
65
+ }
66
+
67
+ // Page content stays in the request. A known revision is a conditional read, never a local cache hit.
68
+ function validatePage(query, value) {
69
+ const parsed = sectionResult.safeParse(value);
70
+ const selected = query.blockIds ? new Set(query.blockIds.split(',')) : null;
71
+ if (
72
+ !parsed.success ||
73
+ !revisionPattern.test(value.revision) ||
74
+ !revisionPattern.test(value.checkpoint) ||
75
+ value.scope !== query.scope ||
76
+ value.id !== query.pageId ||
77
+ value.mode !== query.mode ||
78
+ (selected && value.items.some((item) => !selected.has(item.id))) ||
79
+ (value.nextCursor !== null && (value.nextCursor === query.cursor || !value.items.length)) ||
80
+ (query.revision !== undefined && value.revision !== query.revision) ||
81
+ (query.atRevision !== undefined && value.revision !== query.atRevision) ||
82
+ (value.notModified &&
83
+ (value.revision !== query.knownRevision || value.items.length || value.nextCursor)) ||
84
+ byteLength(value) > query.maxBytes
85
+ ) {
86
+ fail('invalid_response', 'The Memory page did not match its selector or response bounds.', {
87
+ status: 502,
88
+ });
89
+ }
90
+ return parsed.data;
91
+ }
92
+
93
+ function isPageUnavailable(error) {
94
+ return (
95
+ error?.status === 404 &&
96
+ ['memory_page_not_found', 'memory_version_not_found'].includes(error.code)
97
+ );
98
+ }
99
+
100
+ const interruption = (error) => ({
101
+ code: error.code,
102
+ ...(Number.isSafeInteger(error.details?.retryAfterSeconds)
103
+ ? { retryAfterSeconds: error.details.retryAfterSeconds }
104
+ : {}),
105
+ ...(Number.isSafeInteger(error.details?.resetAt) ? { resetAt: error.details.resetAt } : {}),
106
+ });
107
+
108
+ // Ordinary delegated GETs independently enforce plan, grants, ACLs and account quota.
109
+ // Keep metadata space outside each page budget. The final check counts actual serialized UTF-8.
110
+ export async function readMemoryPages(client, input) {
111
+ const { scope, pages, epoch, checkpoint } = validateRequest(input);
112
+ const maxBytes = Math.floor((batchBytes - 4096) / pages.length);
113
+ const results = [];
114
+ let snapshot = epoch ? { epoch, checkpoint } : {};
115
+ let stopped;
116
+ let attempted = 0;
117
+ let cursor = 0;
118
+ while (cursor < pages.length && !stopped) {
119
+ // Establish one snapshot before concurrent reads, including when the first page is unavailable.
120
+ const group = pages.slice(cursor, cursor + (snapshot.epoch ? 2 : 1));
121
+ cursor += group.length;
122
+ attempted += group.length;
123
+ const reads = await Promise.allSettled(
124
+ group.map(async (page) => {
125
+ const query = {
126
+ scope,
127
+ ...page,
128
+ ...(page.blockIds ? { blockIds: page.blockIds.join(',') } : {}),
129
+ ...snapshot,
130
+ maxBytes,
131
+ };
132
+ delete query.accessRevision;
133
+ return validatePage(query, await client.get('memory/sections', query));
134
+ }),
135
+ );
136
+ // A global refusal discards every successful read, including siblings already in flight.
137
+ for (const read of reads) {
138
+ if (
139
+ read.status === 'rejected' &&
140
+ !isPageUnavailable(read.reason) &&
141
+ read.reason?.status !== 429 &&
142
+ !(read.reason?.status === 409 && read.reason.code === 'memory_revision_changed')
143
+ ) {
144
+ throw read.reason;
145
+ }
146
+ }
147
+ for (const [index, read] of reads.entries()) {
148
+ const pageId = group[index].pageId;
149
+ if (read.status === 'rejected') {
150
+ const error = read.reason;
151
+ if (isPageUnavailable(error)) {
152
+ results.push({ pageId, status: 'unavailable' });
153
+ } else if (error.status === 409) {
154
+ results.push({ pageId, status: 'changed' });
155
+ } else {
156
+ stopped = error;
157
+ results.push({ pageId, status: 'deferred' });
158
+ }
159
+ continue;
160
+ }
161
+ const {
162
+ id,
163
+ epoch,
164
+ checkpoint,
165
+ accessRevision,
166
+ title,
167
+ revision,
168
+ mode,
169
+ items,
170
+ nextCursor,
171
+ notModified,
172
+ } = read.value;
173
+ if (
174
+ (snapshot.epoch !== undefined &&
175
+ (epoch !== snapshot.epoch || checkpoint !== snapshot.checkpoint)) ||
176
+ (snapshot.accessRevision !== undefined && accessRevision !== snapshot.accessRevision)
177
+ ) {
178
+ fail(
179
+ 'memory_read_context_changed',
180
+ 'Memory or access changed during this read. Restart from the authorized tree.',
181
+ { status: 409 },
182
+ );
183
+ }
184
+ snapshot = { epoch, checkpoint, accessRevision };
185
+ results.push({
186
+ pageId: id,
187
+ status: notModified ? 'unchanged' : nextCursor ? 'partial' : 'complete',
188
+ title,
189
+ revision,
190
+ mode,
191
+ items,
192
+ nextCursor,
193
+ });
194
+ }
195
+ }
196
+ if (stopped && results.every((page) => page.status === 'deferred')) {
197
+ throw stopped;
198
+ }
199
+ for (const page of pages.slice(cursor)) {
200
+ results.push({ pageId: page.pageId, status: 'deferred' });
201
+ }
202
+ const complete = results.filter(
203
+ (page) => page.status === 'complete' || page.status === 'unchanged',
204
+ ).length;
205
+ const result = {
206
+ scope,
207
+ ...snapshot,
208
+ requested: pages.length,
209
+ attempted,
210
+ complete,
211
+ partial: complete !== pages.length,
212
+ ...(stopped ? { interruption: interruption(stopped) } : {}),
213
+ pages: results,
214
+ };
215
+ if (byteLength(result) > batchBytes) {
216
+ fail('invalid_response', 'The combined Memory result exceeded the byte limit.', {
217
+ status: 502,
218
+ });
219
+ }
220
+ return result;
221
+ }