@yougrowai/node 0.5.0 → 0.6.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.
@@ -0,0 +1,123 @@
1
+ import { type RemovedCounts } from "./scan.js";
2
+ import { type HookPaths, type SessionState } from "./state.js";
3
+ /**
4
+ * A coding session's transcript, read and sent from the person's computer (K's Work slice,
5
+ * decision S10). The hook reads only new complete lines of Claude Code's own file, from where it
6
+ * stopped; keeps what Work keeps, as Work keeps it, after the scan; gzips the kept lines into parts
7
+ * of at most 4 MiB; and sends each to `PUT /api/v2/work/sessions/{id}/transcript/{part}`, where
8
+ * Work scans it again before it is kept.
9
+ *
10
+ * Kept: every message, tool call and tool result, and every compaction summary. Left out, so they
11
+ * never leave the computer: Claude Code's own bookkeeping (request caches, file history backups,
12
+ * queue and screen state, the folder on each line), thinking signatures, images, and subagents'
13
+ * own lines. A tool result that read a secret file (.env.local, a key file) goes whole. A line
14
+ * longer than Work keeps goes as its label: its ids and size, none of its words.
15
+ *
16
+ * The line reader below, to the next rule, is the same as the app's src/lib/work/sessions/lines.ts:
17
+ * change both together. test/workHook.transcript.test.ts holds both to the same answers.
18
+ */
19
+ /** The longest line Work keeps; a longer one is cut to a label. */
20
+ export declare const TRANSCRIPT_LINE_MAX: number;
21
+ /** What carries from one part to the next: the tool calls that read a secret file, waiting for their results. */
22
+ export interface LineScanState {
23
+ secretCalls: Array<{
24
+ id: string;
25
+ file: string;
26
+ }>;
27
+ }
28
+ export declare const emptyScanState: () => LineScanState;
29
+ export type LineRefusal = "not_transcript" | "other_session";
30
+ export type LineOutcome = {
31
+ kind: "kept";
32
+ line: Record<string, unknown>;
33
+ json: string;
34
+ removed: RemovedCounts;
35
+ hookRemoved: RemovedCounts;
36
+ } | {
37
+ kind: "left_out";
38
+ } | {
39
+ kind: "refused";
40
+ why: LineRefusal;
41
+ };
42
+ /**
43
+ * One line as Claude Code wrote it, parsed: kept (picked, scanned, as one line of JSON), left out,
44
+ * or refused. `state` carries the tool calls that read a secret file to their results, across
45
+ * lines and parts; it is changed in place.
46
+ */
47
+ export declare function readTranscriptLine(text: string, o: {
48
+ agentSessionId: string;
49
+ state: LineScanState;
50
+ }): LineOutcome;
51
+ /**
52
+ * A line longer than Work keeps, as the label that takes its place: its type, id and time when its
53
+ * first bytes say them, and how long it was. None of its words are kept, since a cut line can't be
54
+ * read whole to be scanned. Refused when its first bytes name another session.
55
+ */
56
+ export declare function cutTranscriptLine(head: string, bytes: number, agentSessionId: string): LineOutcome;
57
+ /** A part as sent, gzipped, at most; and its kept lines before gzip, aimed at. */
58
+ export declare const PART_MAX_BYTES: number;
59
+ export declare const PART_TARGET_BYTES: number;
60
+ /** Raw bytes one part reads at most: a stretch of bookkeeping lines never makes it read on and on. */
61
+ export declare const PART_READ_BYTES: number;
62
+ /** A raw line longer than this is cut from its first bytes, without being read whole. */
63
+ export declare const RAW_LINE_MAX: number;
64
+ /** One complete line of the file: its words (or, when too long to read, its first bytes) and where it ends. */
65
+ export interface RawLine {
66
+ text: string | null;
67
+ head: string;
68
+ bytes: number;
69
+ /** The offset just past its newline: where the next line starts. */
70
+ end: number;
71
+ }
72
+ /** The file's complete lines from `from`, as they come; a last line with no newline yet is Claude Code still writing it, and waits. */
73
+ export declare function completeLines(file: string, from: number, maxRead?: number): Generator<RawLine>;
74
+ /** One line as the hook sends it: kept (as JSON), or left out. A line Work would refuse is left out here, so a part is never refused for it. */
75
+ export declare function sendableLine(raw: RawLine, agentSessionId: string, state: LineScanState): string | null;
76
+ export interface BuiltPart {
77
+ /** The kept lines, gzipped; empty when the stretch held nothing Work keeps. */
78
+ body: Buffer;
79
+ lines: number;
80
+ /** Where the part ends in Claude Code's file: X-Work-Offset. */
81
+ end: number;
82
+ /** The scan's running state after this part, kept once Work has the part. */
83
+ scan: LineScanState;
84
+ }
85
+ /** The next part from `from`, aiming at `target` kept bytes; null when no new complete line is there. */
86
+ export declare function buildPart(file: string, from: number, scan: LineScanState, o: {
87
+ agentSessionId: string;
88
+ target?: number;
89
+ }): BuiltPart | null;
90
+ /** What Work answered a request: its status and JSON body; 0 when it didn't answer. */
91
+ export interface HttpAnswer {
92
+ status: number;
93
+ body: Record<string, unknown> | null;
94
+ retryAfter: number | null;
95
+ }
96
+ export type PartSender = (o: {
97
+ session: string;
98
+ part: number;
99
+ offset: number;
100
+ scan: number;
101
+ body: Buffer;
102
+ }) => Promise<HttpAnswer>;
103
+ /** What is left to send of a chat's transcript, in bytes of Claude Code's file. */
104
+ export declare function unsentBytes(s: Pick<SessionState, "transcriptPath" | "offset">): number;
105
+ export type SendOutcome = "sent" | "nothing" | "off" | "busy" | "failed";
106
+ /** What the next start prints when Work took no part from this hook's scan, before Work's own words. */
107
+ export declare const HOOK_OLD_LINE = "Work isn't keeping this chat's transcript: the hook on this computer is out of date.";
108
+ /**
109
+ * Send a chat's new transcript lines, at most `maxParts` parts and until `deadline`, with its lock
110
+ * held so two hooks never send the same chat at once. Every answer moves the state on: a kept part
111
+ * moves the offset, a part Work kept already or a part out of order takes Work's own place, and a
112
+ * refusal that won't change by sending again turns sending off until Work's next answer.
113
+ */
114
+ export declare function sendTranscript(o: {
115
+ paths: HookPaths;
116
+ agentSessionId: string;
117
+ put: PartSender;
118
+ now: () => number;
119
+ maxParts: number;
120
+ deadline: number;
121
+ }): Promise<SendOutcome>;
122
+ /** Whether a Stop should send now: half a megabyte waiting, or anything waiting for ten minutes. */
123
+ export declare function partDue(s: Pick<SessionState, "transcriptPath" | "offset" | "lastPartAt" | "startedAt" | "transcript">, now: number): boolean;
@@ -0,0 +1,415 @@
1
+ import * as fs from "node:fs";
2
+ import { gzipSync } from "node:zlib";
3
+ import { addRemoved, labelsIn, removedLabel, scanText, secretFileOfCall, secretFileName, SCAN_VERSION } from "./scan.js";
4
+ import { keepNotice, lockFile, readState, takeLock, updateState } from "./state.js";
5
+ /**
6
+ * A coding session's transcript, read and sent from the person's computer (K's Work slice,
7
+ * decision S10). The hook reads only new complete lines of Claude Code's own file, from where it
8
+ * stopped; keeps what Work keeps, as Work keeps it, after the scan; gzips the kept lines into parts
9
+ * of at most 4 MiB; and sends each to `PUT /api/v2/work/sessions/{id}/transcript/{part}`, where
10
+ * Work scans it again before it is kept.
11
+ *
12
+ * Kept: every message, tool call and tool result, and every compaction summary. Left out, so they
13
+ * never leave the computer: Claude Code's own bookkeeping (request caches, file history backups,
14
+ * queue and screen state, the folder on each line), thinking signatures, images, and subagents'
15
+ * own lines. A tool result that read a secret file (.env.local, a key file) goes whole. A line
16
+ * longer than Work keeps goes as its label: its ids and size, none of its words.
17
+ *
18
+ * The line reader below, to the next rule, is the same as the app's src/lib/work/sessions/lines.ts:
19
+ * change both together. test/workHook.transcript.test.ts holds both to the same answers.
20
+ */
21
+ /** The longest line Work keeps; a longer one is cut to a label. */
22
+ export const TRANSCRIPT_LINE_MAX = 1024 * 1024;
23
+ /** The line types kept: messages, and the system line that marks a compaction. */
24
+ const KEPT_TYPES = new Set(["user", "assistant", "system", "summary"]);
25
+ /** The fields a kept line keeps; the rest is Claude Code's own bookkeeping, a full path among it. */
26
+ const LINE_FIELDS = ["type", "subtype", "uuid", "parentUuid", "logicalParentUuid", "sessionId", "timestamp", "isCompactSummary", "isMeta", "compactMetadata", "summary", "leafUuid", "content", "message"];
27
+ const MESSAGE_FIELDS = ["role", "model", "content"];
28
+ /** Fields that hold ids and fixed words, never text anyone wrote: not scanned. */
29
+ const NOT_SCANNED = new Set(["type", "subtype", "uuid", "parentUuid", "logicalParentUuid", "sessionId", "timestamp", "tool_use_id", "role", "model", "leafUuid", "trigger"]);
30
+ /** How many tool calls that read a secret file a session remembers until their results come. */
31
+ const SECRET_CALLS_KEPT = 50;
32
+ export const emptyScanState = () => ({ secretCalls: [] });
33
+ const isObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
34
+ /** Every string in a value through the scan; ids, fixed words and the labels put in already are left as they are. */
35
+ function scanDeep(v, removed, key, depth = 0) {
36
+ if (typeof v === "string") {
37
+ if (key !== null && NOT_SCANNED.has(key))
38
+ return v;
39
+ removed.hook = addRemoved(removed.hook, labelsIn(v));
40
+ const r = scanText(v);
41
+ removed.server = addRemoved(removed.server, r.removed);
42
+ return r.text;
43
+ }
44
+ if (depth > 40)
45
+ return null;
46
+ if (Array.isArray(v))
47
+ return v.map((x) => scanDeep(x, removed, null, depth + 1));
48
+ if (isObject(v)) {
49
+ if (removed.done.has(v))
50
+ return v;
51
+ const out = {};
52
+ for (const [k, x] of Object.entries(v))
53
+ out[k] = scanDeep(x, removed, k, depth + 1);
54
+ return out;
55
+ }
56
+ return v;
57
+ }
58
+ /** A block Work put in itself: kept as it is, never scanned or counted again. */
59
+ function final(counts, block) {
60
+ counts.done.add(block);
61
+ return block;
62
+ }
63
+ function remember(state, id, file) {
64
+ state.secretCalls = [...state.secretCalls.filter((c) => c.id !== id), { id, file }].slice(-SECRET_CALLS_KEPT);
65
+ }
66
+ /** A tool result's content, whole, as the label for the secret file it read. */
67
+ function secretResult(block, file, counts) {
68
+ const label = removedLabel("secret_file", file);
69
+ // The hook replaced it already: count its label, not a second removal.
70
+ const already = typeof block.content === "string" && block.content === label;
71
+ if (already)
72
+ counts.hook = addRemoved(counts.hook, { secret_file: 1 });
73
+ else
74
+ counts.server = addRemoved(counts.server, { secret_file: 1 });
75
+ const out = { type: "tool_result", tool_use_id: block.tool_use_id, ...(block.is_error === true ? { is_error: true } : {}), content: label };
76
+ counts.done.add(out);
77
+ return out;
78
+ }
79
+ /** A message's blocks as kept: images to their label, thinking without its signature, unknown blocks left out. */
80
+ function keptBlocks(blocks, state, counts, secretOfLine) {
81
+ const out = [];
82
+ for (const b of blocks) {
83
+ if (typeof b === "string") {
84
+ out.push(b);
85
+ continue;
86
+ }
87
+ if (!isObject(b) || typeof b.type !== "string")
88
+ continue;
89
+ switch (b.type) {
90
+ case "text":
91
+ if (typeof b.text === "string")
92
+ out.push({ type: "text", text: b.text });
93
+ break;
94
+ case "thinking":
95
+ if (typeof b.thinking === "string" && b.thinking)
96
+ out.push({ type: "thinking", thinking: b.thinking });
97
+ break;
98
+ case "image":
99
+ counts.server = addRemoved(counts.server, { image: 1 });
100
+ out.push(final(counts, { type: "text", text: removedLabel("image") }));
101
+ break;
102
+ case "tool_use": {
103
+ const name = typeof b.name === "string" ? b.name : "";
104
+ const id = typeof b.id === "string" ? b.id : "";
105
+ const file = secretFileOfCall(name, b.input);
106
+ if (file && id)
107
+ remember(state, id, file);
108
+ out.push({ type: "tool_use", id, name, input: b.input ?? {} });
109
+ break;
110
+ }
111
+ case "tool_result": {
112
+ const id = typeof b.tool_use_id === "string" ? b.tool_use_id : "";
113
+ const call = state.secretCalls.find((c) => c.id === id);
114
+ const file = call?.file ?? secretOfLine;
115
+ if (file) {
116
+ out.push(secretResult(b, file, counts));
117
+ if (call)
118
+ state.secretCalls = state.secretCalls.filter((c) => c.id !== id);
119
+ break;
120
+ }
121
+ const content = Array.isArray(b.content) ? keptBlocks(b.content, state, counts, null) : typeof b.content === "string" ? b.content : "";
122
+ out.push({ type: "tool_result", tool_use_id: id, ...(b.is_error === true ? { is_error: true } : {}), content });
123
+ break;
124
+ }
125
+ default:
126
+ // Redacted thinking, documents and anything new: data with no words Work needs.
127
+ break;
128
+ }
129
+ }
130
+ return out;
131
+ }
132
+ /**
133
+ * One line as Claude Code wrote it, parsed: kept (picked, scanned, as one line of JSON), left out,
134
+ * or refused. `state` carries the tool calls that read a secret file to their results, across
135
+ * lines and parts; it is changed in place.
136
+ */
137
+ export function readTranscriptLine(text, o) {
138
+ if (!text.trim())
139
+ return { kind: "left_out" };
140
+ let raw;
141
+ try {
142
+ raw = JSON.parse(text);
143
+ }
144
+ catch {
145
+ return { kind: "refused", why: "not_transcript" };
146
+ }
147
+ if (!isObject(raw) || typeof raw.type !== "string")
148
+ return { kind: "refused", why: "not_transcript" };
149
+ if (typeof raw.sessionId === "string" && raw.sessionId !== o.agentSessionId)
150
+ return { kind: "refused", why: "other_session" };
151
+ if (raw.type === "cut")
152
+ return cutByHook(raw);
153
+ if (!KEPT_TYPES.has(raw.type) || raw.isSidechain === true)
154
+ return { kind: "left_out" };
155
+ if (raw.type === "system" && raw.subtype !== "compact_boundary")
156
+ return { kind: "left_out" };
157
+ const counts = { server: {}, hook: {}, done: new WeakSet() };
158
+ const picked = {};
159
+ for (const f of LINE_FIELDS)
160
+ if (raw[f] !== undefined && f !== "message")
161
+ picked[f] = raw[f];
162
+ // A Read of a secret file, as Claude Code's own result notes it, even if its call was in a part Work never saw.
163
+ const used = isObject(raw.toolUseResult) && isObject(raw.toolUseResult.file) && typeof raw.toolUseResult.file.filePath === "string" ? secretFileName(raw.toolUseResult.file.filePath) : null;
164
+ if (isObject(raw.message)) {
165
+ const m = {};
166
+ for (const f of MESSAGE_FIELDS)
167
+ if (raw.message[f] !== undefined)
168
+ m[f] = raw.message[f];
169
+ if (Array.isArray(m.content))
170
+ m.content = keptBlocks(m.content, o.state, counts, used);
171
+ picked.message = m;
172
+ }
173
+ const line = scanDeep(picked, counts, null);
174
+ return { kind: "kept", line, json: JSON.stringify(line), removed: counts.server, hookRemoved: counts.hook };
175
+ }
176
+ /** "2.1 MB", for a cut line's label. */
177
+ function mb(bytes) {
178
+ return `${(bytes / 1_000_000).toFixed(1)} MB`;
179
+ }
180
+ /** A cut line's ids, as its first bytes or the hook say them. */
181
+ const CUT_FIELD = /^[A-Za-z0-9_:.+-]{1,80}$/;
182
+ function cutLine(f, bytes) {
183
+ const line = {
184
+ type: "cut",
185
+ cutType: f.cutType,
186
+ uuid: f.uuid,
187
+ timestamp: f.timestamp,
188
+ bytes,
189
+ text: `[cut: this line was ${mb(bytes)}, more than the ${mb(TRANSCRIPT_LINE_MAX)} a line Work keeps]`,
190
+ };
191
+ return { kind: "kept", line, json: JSON.stringify(line), removed: {}, hookRemoved: {} };
192
+ }
193
+ /**
194
+ * A line longer than Work keeps, as the label that takes its place: its type, id and time when its
195
+ * first bytes say them, and how long it was. None of its words are kept, since a cut line can't be
196
+ * read whole to be scanned. Refused when its first bytes name another session.
197
+ */
198
+ export function cutTranscriptLine(head, bytes, agentSessionId) {
199
+ const field = (name) => new RegExp(`"${name}"\\s*:\\s*"([A-Za-z0-9_:.+-]{1,80})"`).exec(head)?.[1] ?? null;
200
+ const sessionId = field("sessionId");
201
+ if (sessionId && sessionId !== agentSessionId)
202
+ return { kind: "refused", why: "other_session" };
203
+ return cutLine({ cutType: field("type"), uuid: field("uuid"), timestamp: field("timestamp") }, bytes);
204
+ }
205
+ /** A line the hook cut on the computer: its label rebuilt from the ids and size alone. One that isn't longer than Work keeps is left out. */
206
+ function cutByHook(raw) {
207
+ const id = (v) => (typeof v === "string" && CUT_FIELD.test(v) ? v : null);
208
+ const bytes = raw.bytes;
209
+ if (typeof bytes !== "number" || !Number.isSafeInteger(bytes) || bytes <= TRANSCRIPT_LINE_MAX)
210
+ return { kind: "left_out" };
211
+ return cutLine({ cutType: id(raw.cutType), uuid: id(raw.uuid), timestamp: id(raw.timestamp) }, bytes);
212
+ }
213
+ // --- Reading new lines, building parts, sending them ---------------------------------------------
214
+ /** A part as sent, gzipped, at most; and its kept lines before gzip, aimed at. */
215
+ export const PART_MAX_BYTES = 4 * 1024 * 1024;
216
+ export const PART_TARGET_BYTES = 6 * 1024 * 1024;
217
+ /** Raw bytes one part reads at most: a stretch of bookkeeping lines never makes it read on and on. */
218
+ export const PART_READ_BYTES = 48 * 1024 * 1024;
219
+ /** A raw line longer than this is cut from its first bytes, without being read whole. */
220
+ export const RAW_LINE_MAX = 16 * 1024 * 1024;
221
+ const HEAD_BYTES = 4096;
222
+ const CHUNK = 1024 * 1024;
223
+ /** The file's complete lines from `from`, as they come; a last line with no newline yet is Claude Code still writing it, and waits. */
224
+ export function* completeLines(file, from, maxRead = PART_READ_BYTES) {
225
+ let fd;
226
+ try {
227
+ fd = fs.openSync(file, "r");
228
+ }
229
+ catch {
230
+ return;
231
+ }
232
+ try {
233
+ const buf = Buffer.alloc(CHUNK);
234
+ let pos = from;
235
+ let pending = [];
236
+ let pendingLen = 0;
237
+ let head = null;
238
+ // Past `maxRead`, only to finish the line it is in: a line too long to keep still reaches its end.
239
+ while (pos - from < maxRead || pendingLen > 0) {
240
+ const n = fs.readSync(fd, buf, 0, CHUNK, pos);
241
+ if (n <= 0)
242
+ return;
243
+ let start = 0;
244
+ while (start < n) {
245
+ const nl = buf.indexOf(10, start);
246
+ const stop = nl === -1 || nl >= n ? n : nl;
247
+ const piece = buf.subarray(start, stop);
248
+ if (head === null && pendingLen + piece.length > RAW_LINE_MAX) {
249
+ head = Buffer.concat([...pending, piece]).subarray(0, HEAD_BYTES);
250
+ pending = [];
251
+ }
252
+ if (head === null)
253
+ pending.push(Buffer.from(piece));
254
+ pendingLen += piece.length;
255
+ if (stop === n)
256
+ break;
257
+ const end = pos + nl + 1;
258
+ const whole = head === null ? Buffer.concat(pending) : null;
259
+ yield { text: whole ? whole.toString("utf8") : null, head: (whole ?? head).subarray(0, HEAD_BYTES).toString("utf8"), bytes: pendingLen, end };
260
+ pending = [];
261
+ pendingLen = 0;
262
+ head = null;
263
+ start = nl + 1;
264
+ }
265
+ pos += n;
266
+ }
267
+ }
268
+ finally {
269
+ fs.closeSync(fd);
270
+ }
271
+ }
272
+ /** One line as the hook sends it: kept (as JSON), or left out. A line Work would refuse is left out here, so a part is never refused for it. */
273
+ export function sendableLine(raw, agentSessionId, state) {
274
+ if (raw.text === null) {
275
+ const r = cutTranscriptLine(raw.head, raw.bytes, agentSessionId);
276
+ return r.kind === "kept" ? r.json : null;
277
+ }
278
+ const r = readTranscriptLine(raw.text, { agentSessionId, state });
279
+ if (r.kind !== "kept")
280
+ return null;
281
+ if (Buffer.byteLength(r.json) <= TRANSCRIPT_LINE_MAX)
282
+ return r.json;
283
+ // Longer than Work keeps even without its bookkeeping: its label, with the ids and size only.
284
+ const cut = cutTranscriptLine(raw.head, Math.max(raw.bytes, TRANSCRIPT_LINE_MAX + 1), agentSessionId);
285
+ return cut.kind === "kept" ? cut.json : null;
286
+ }
287
+ /** The next part from `from`, aiming at `target` kept bytes; null when no new complete line is there. */
288
+ export function buildPart(file, from, scan, o) {
289
+ const target = o.target ?? PART_TARGET_BYTES;
290
+ const state = { secretCalls: scan.secretCalls.map((c) => ({ ...c })) };
291
+ const kept = [];
292
+ let keptBytes = 0;
293
+ let end = from;
294
+ for (const raw of completeLines(file, from)) {
295
+ const json = sendableLine(raw, o.agentSessionId, state);
296
+ end = raw.end;
297
+ if (json !== null) {
298
+ kept.push(json);
299
+ keptBytes += Buffer.byteLength(json) + 1;
300
+ }
301
+ if (keptBytes >= target)
302
+ break;
303
+ }
304
+ if (end === from)
305
+ return null;
306
+ return { body: kept.length ? gzipSync(Buffer.from(`${kept.join("\n")}\n`, "utf8")) : Buffer.alloc(0), lines: kept.length, end, scan: state };
307
+ }
308
+ const num = (v) => (typeof v === "number" && Number.isSafeInteger(v) && v >= 0 ? v : null);
309
+ const text = (v, fallback) => (typeof v === "string" && v ? v.slice(0, 600) : fallback);
310
+ /** What is left to send of a chat's transcript, in bytes of Claude Code's file. */
311
+ export function unsentBytes(s) {
312
+ if (!s.transcriptPath)
313
+ return 0;
314
+ try {
315
+ return Math.max(0, fs.statSync(s.transcriptPath).size - s.offset);
316
+ }
317
+ catch {
318
+ return 0;
319
+ }
320
+ }
321
+ /** What the next start prints when Work took no part from this hook's scan, before Work's own words. */
322
+ export const HOOK_OLD_LINE = "Work isn't keeping this chat's transcript: the hook on this computer is out of date.";
323
+ /**
324
+ * Send a chat's new transcript lines, at most `maxParts` parts and until `deadline`, with its lock
325
+ * held so two hooks never send the same chat at once. Every answer moves the state on: a kept part
326
+ * moves the offset, a part Work kept already or a part out of order takes Work's own place, and a
327
+ * refusal that won't change by sending again turns sending off until Work's next answer.
328
+ */
329
+ export async function sendTranscript(o) {
330
+ const first = readState(o.paths, o.agentSessionId);
331
+ if (!first?.session || !first.transcriptPath || first.transcript?.on !== true)
332
+ return "nothing";
333
+ const release = takeLock(lockFile(o.paths, o.agentSessionId), o.now());
334
+ if (!release)
335
+ return "busy";
336
+ let outcome = "nothing";
337
+ try {
338
+ let resyncs = 0;
339
+ let target = PART_TARGET_BYTES;
340
+ for (let sent = 0; sent < o.maxParts && o.now() < o.deadline;) {
341
+ const s = readState(o.paths, o.agentSessionId);
342
+ if (!s?.session || !s.transcriptPath || s.transcript?.on !== true)
343
+ break;
344
+ const part = buildPart(s.transcriptPath, s.offset, s.scan, { agentSessionId: s.agentSessionId, target });
345
+ if (!part)
346
+ break;
347
+ const set = (change) => updateState(o.paths, o.agentSessionId, o.now(), (cur) => ({ ...cur, ...change }));
348
+ if (part.lines === 0) {
349
+ // Nothing Work keeps in this stretch: move on without a part.
350
+ set({ offset: part.end, scan: part.scan });
351
+ continue;
352
+ }
353
+ if (part.body.length > PART_MAX_BYTES) {
354
+ if (target <= 64 * 1024)
355
+ break;
356
+ target = Math.floor(target / 2);
357
+ continue;
358
+ }
359
+ const a = await o.put({ session: s.session, part: s.nextPart, offset: part.end, scan: SCAN_VERSION, body: part.body });
360
+ const b = a.body ?? {};
361
+ const error = typeof b.error === "string" ? b.error : null;
362
+ if (a.status === 201 || a.status === 200) {
363
+ const nextPart = num(b.nextPart) ?? s.nextPart + 1;
364
+ const offset = num(b.offset);
365
+ if (a.status === 201 || offset === part.end)
366
+ set({ offset: part.end, scan: part.scan, nextPart, lastPartAt: o.now() });
367
+ else
368
+ set({ offset: Math.max(s.offset, offset ?? s.offset), nextPart });
369
+ sent += 1;
370
+ outcome = "sent";
371
+ target = PART_TARGET_BYTES;
372
+ continue;
373
+ }
374
+ if (a.status === 409 && (error === "part_order" || error === "part_offset") && resyncs < 3) {
375
+ resyncs += 1;
376
+ set({ nextPart: num(b.nextPart) ?? s.nextPart, offset: Math.max(s.offset, num(b.offset) ?? 0) });
377
+ continue;
378
+ }
379
+ if (a.status === 409 && error === "hook_old") {
380
+ // Work takes no part from this hook's scan: the next start says so, once, and no chat sends again.
381
+ const message = text(b.message, "Update the hook.");
382
+ keepNotice(o.paths, `${HOOK_OLD_LINE} ${message}`);
383
+ set({ transcript: { on: false, why: "hook_old", message } });
384
+ return "off";
385
+ }
386
+ if (a.status === 400 && (error === "not_transcript" || error === "other_session")) {
387
+ // Work won't take these lines however often they come: move past them.
388
+ set({ offset: part.end, scan: part.scan, refusedParts: s.refusedParts + 1 });
389
+ continue;
390
+ }
391
+ if (a.status === 413 && target > 64 * 1024) {
392
+ target = Math.floor(target / 2);
393
+ continue;
394
+ }
395
+ if (a.status === 429 || a.status === 0 || a.status >= 500)
396
+ return outcome === "sent" ? "sent" : "failed";
397
+ // Off for this key, this organisation or this copy, the session gone or full, or the key stopped.
398
+ set({ transcript: { on: false, why: error ?? `status_${a.status}`, message: text(b.message, "Work isn't keeping this transcript now.") } });
399
+ return "off";
400
+ }
401
+ }
402
+ finally {
403
+ release();
404
+ }
405
+ return outcome;
406
+ }
407
+ /** Whether a Stop should send now: half a megabyte waiting, or anything waiting for ten minutes. */
408
+ export function partDue(s, now) {
409
+ if (s.transcript?.on !== true)
410
+ return false;
411
+ const waiting = unsentBytes(s);
412
+ if (waiting <= 0)
413
+ return false;
414
+ return waiting >= 512 * 1024 || now - (s.lastPartAt ?? s.startedAt) >= 10 * 60_000;
415
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yougrowai/node",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "Keep your users' state in YouGrow lifecycle journeys, and verify the requests YouGrow sends you.",
5
5
  "license": "MIT",
6
6
  "author": "YouGrow.AI Limited",
@@ -25,6 +25,7 @@
25
25
  },
26
26
  "./package.json": "./package.json"
27
27
  },
28
+ "bin": { "work-hook": "./dist/workHook/cli.js" },
28
29
  "typesVersions": {
29
30
  "*": { "server": ["./dist/cjs/server.d.ts"] }
30
31
  },