@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 281 lines 9.02 KB
Raw
1 /**
2 * pkt-line framing (gitprotocol-common).
3 *
4 * Every protocol message except raw pack bytes is a stream of pkt-lines:
5 * 4 lowercase hex digits (total length INCLUDING the 4 length bytes) followed
6 * by the payload. Max total length 65520 ⇒ max payload 65516.
7 *
8 * Special packets whose length field is not a length:
9 *
10 * | bytes | meaning |
11 * |--------|--------------------------------------------|
12 * | `0000` | flush-pkt — end of message/request/response |
13 * | `0001` | delim-pkt — section separator (v2) |
14 * | `0002` | response-end-pkt (v2, stateless) |
15 *
16 * Readers MUST strip an optional trailing LF from text payloads; writers
17 * SHOULD append one. `ERR <msg>` payloads report in-band fatals once a 200
18 * has begun.
19 */
20 import * as Arr from "effect/Array";
21 import * as Cause from "effect/Cause";
22 import * as Effect from "effect/Effect";
23 import * as Pull from "effect/Pull";
24 import * as Schema from "effect/Schema";
25 import * as Stream from "effect/Stream";
26 import { concatBytes, utf8Decode, utf8Encode } from "./ObjectCodec.ts";
27
28 /**
29 * Maximum pkt-line payload: 65520 total − 4 length bytes.
30 */
31 export const MAX_PKT_PAYLOAD = 65516;
32
33 /**
34 * Error raised on malformed pkt-line framing (bad hex length, out-of-range
35 * length, truncated payload, oversize writer payload).
36 */
37 export class PktLineError extends Schema.TaggedError<PktLineError>()("PktLineError", {
38 reason: Schema.String,
39 }) {}
40
41 /**
42 * Error raised when a syntactically valid pkt-line stream contains a request
43 * the protocol grammar does not allow (bad `want`/`have`/command lines,
44 * unsupported arguments). Shared by `UploadPack` and `ReceivePack`.
45 */
46 export class ProtocolError extends Schema.TaggedError<ProtocolError>()("ProtocolError", {
47 reason: Schema.String,
48 }) {}
49
50 /**
51 * One decoded pkt-line: a data packet with its payload, or one of the three
52 * special packets.
53 */
54 export type PktLine =
55 | { readonly _tag: "data"; readonly payload: Uint8Array }
56 | { readonly _tag: "flush" }
57 | { readonly _tag: "delim" }
58 | { readonly _tag: "responseEnd" };
59
60 /** The flush packet singleton. */
61 export const flush: PktLine = { _tag: "flush" };
62 /** The delim packet singleton. */
63 export const delim: PktLine = { _tag: "delim" };
64
65 /** The 4 raw bytes of a flush-pkt (`0000`). */
66 export const flushPkt: Uint8Array = utf8Encode("0000");
67 /** The 4 raw bytes of a delim-pkt (`0001`). */
68 export const delimPkt: Uint8Array = utf8Encode("0001");
69
70 const HEX_CHARS = "0123456789abcdef";
71
72 const encodeLength = (n: number): Uint8Array => {
73 const out = new Uint8Array(4);
74 out[0] = HEX_CHARS.charCodeAt((n >> 12) & 0xf);
75 out[1] = HEX_CHARS.charCodeAt((n >> 8) & 0xf);
76 out[2] = HEX_CHARS.charCodeAt((n >> 4) & 0xf);
77 out[3] = HEX_CHARS.charCodeAt(n & 0xf);
78 return out;
79 };
80
81 /**
82 * Encodes a data pkt-line around a binary payload (no LF appended). Throws
83 * {@link PktLineError} when the payload exceeds {@link MAX_PKT_PAYLOAD} —
84 * an internal invariant violation, since all writers cap their payloads.
85 */
86 export const pktLine = (payload: Uint8Array): Uint8Array => {
87 if (payload.length > MAX_PKT_PAYLOAD) {
88 throw PktLineError.make({
89 reason: `pkt-line payload ${payload.length} exceeds ${MAX_PKT_PAYLOAD}`,
90 });
91 }
92 const out = new Uint8Array(4 + payload.length);
93 out.set(encodeLength(payload.length + 4), 0);
94 out.set(payload, 4);
95 return out;
96 };
97
98 /**
99 * Encodes a text pkt-line, appending the conventional trailing LF when the
100 * text does not already end with one.
101 */
102 export const pktText = (text: string): Uint8Array =>
103 pktLine(utf8Encode(text.endsWith("\n") ? text : `${text}\n`));
104
105 /**
106 * Encodes an `ERR ` pkt-line. Usable anywhere in a response (including in
107 * place of an advertisement); the client prints `remote error: <message>`
108 * and aborts.
109 */
110 export const errPkt = (message: string): Uint8Array => pktText(`ERR ${message}`);
111
112 /**
113 * Decodes a data pkt-line payload as UTF-8 text with the optional trailing
114 * LF stripped (readers MUST strip it).
115 */
116 export const pktPayloadText = (payload: Uint8Array): string => {
117 const trimmed =
118 payload.length > 0 && payload[payload.length - 1] === 0x0a
119 ? payload.subarray(0, payload.length - 1)
120 : payload;
121 return utf8Decode(trimmed);
122 };
123
124 /**
125 * Result of attempting to read one pkt-line at an offset.
126 */
127 export type PktReadResult =
128 | { readonly _tag: "pkt"; readonly pkt: PktLine; readonly next: number }
129 | { readonly _tag: "incomplete" }
130 | { readonly _tag: "invalid"; readonly reason: string };
131
132 const hexDigit = (byte: number): number => {
133 if (byte >= 0x30 && byte <= 0x39) return byte - 0x30;
134 if (byte >= 0x61 && byte <= 0x66) return byte - 0x61 + 10;
135 if (byte >= 0x41 && byte <= 0x46) return byte - 0x41 + 10;
136 return -1;
137 };
138
139 /**
140 * Attempts to read one pkt-line from `buf` at `offset` without copying.
141 * Returns `incomplete` when more bytes are needed, `invalid` on malformed
142 * framing, or the decoded packet and the offset of the next one.
143 */
144 export const readPktLineAt = (buf: Uint8Array, offset: number): PktReadResult => {
145 if (offset + 4 > buf.length) return { _tag: "incomplete" };
146 let n = 0;
147 for (let i = 0; i < 4; i++) {
148 const d = hexDigit(buf[offset + i]!);
149 if (d === -1) {
150 return {
151 _tag: "invalid",
152 reason: `invalid pkt-line length at offset ${offset}`,
153 };
154 }
155 n = (n << 4) | d;
156 }
157 if (n === 0) return { _tag: "pkt", pkt: flush, next: offset + 4 };
158 if (n === 1) return { _tag: "pkt", pkt: delim, next: offset + 4 };
159 if (n === 2) {
160 return { _tag: "pkt", pkt: { _tag: "responseEnd" }, next: offset + 4 };
161 }
162 if (n === 3) {
163 return { _tag: "invalid", reason: `invalid pkt-line length 0003` };
164 }
165 if (n > MAX_PKT_PAYLOAD + 4) {
166 return {
167 _tag: "invalid",
168 reason: `pkt-line length ${n} exceeds maximum 65520`,
169 };
170 }
171 if (offset + n > buf.length) return { _tag: "incomplete" };
172 return {
173 _tag: "pkt",
174 pkt: { _tag: "data", payload: buf.subarray(offset + 4, offset + n) },
175 next: offset + n,
176 };
177 };
178
179 /**
180 * Decodes an entire buffer (from `offset`) as consecutive pkt-lines. Fails
181 * with {@link PktLineError} when the buffer ends mid-packet or contains
182 * malformed framing.
183 */
184 export const decodePktLines = (
185 buf: Uint8Array,
186 offset = 0,
187 ): Effect.Effect<ReadonlyArray<PktLine>, PktLineError> =>
188 Effect.suspend(() => {
189 const out: Array<PktLine> = [];
190 let pos = offset;
191 while (pos < buf.length) {
192 const r = readPktLineAt(buf, pos);
193 switch (r._tag) {
194 case "pkt":
195 out.push(r.pkt);
196 pos = r.next;
197 break;
198 case "incomplete":
199 return Effect.fail(PktLineError.make({ reason: `truncated pkt-line at offset ${pos}` }));
200 case "invalid":
201 return Effect.fail(PktLineError.make({ reason: r.reason }));
202 }
203 }
204 return Effect.succeed(out);
205 });
206
207 const EMPTY = new Uint8Array(0);
208
209 /**
210 * Stream transform: decodes a byte stream into a stream of pkt-lines,
211 * buffering partial packets across chunk boundaries. Fails with
212 * {@link PktLineError} on malformed framing or a truncated trailing packet.
213 *
214 * Note: payloads are copied out of the internal buffer so they remain valid
215 * after the transform advances.
216 */
217 export const decodePktStream = <E, R>(
218 input: Stream.Stream<Uint8Array, E, R>,
219 ): Stream.Stream<PktLine, E | PktLineError, R> =>
220 Stream.transformPull(input, (pull) =>
221 Effect.sync(() => {
222 let buffer: Uint8Array = EMPTY;
223 let upstreamDone = false;
224
225 const drain = (): Array<PktLine> | PktLineError => {
226 const out: Array<PktLine> = [];
227 let pos = 0;
228 for (;;) {
229 const r = readPktLineAt(buffer, pos);
230 if (r._tag === "incomplete") break;
231 if (r._tag === "invalid") {
232 return PktLineError.make({ reason: r.reason });
233 }
234 // copy the payload: the backing buffer is replaced on refill
235 out.push(
236 r.pkt._tag === "data"
237 ? { _tag: "data", payload: Uint8Array.from(r.pkt.payload) }
238 : r.pkt,
239 );
240 pos = r.next;
241 }
242 buffer = pos === 0 ? buffer : buffer.subarray(pos);
243 return out;
244 };
245
246 const loop: Pull.Pull<
247 Arr.NonEmptyReadonlyArray<PktLine>,
248 E | PktLineError,
249 void
250 > = Effect.suspend(() => {
251 const drained = drain();
252 if (Schema.is(PktLineError)(drained)) return Effect.fail(drained);
253 if (Arr.isReadonlyArrayNonEmpty(drained)) {
254 return Effect.succeed(drained);
255 }
256 if (upstreamDone) {
257 if (buffer.length > 0) {
258 return Effect.fail(
259 PktLineError.make({
260 reason: "byte stream ended inside a pkt-line",
261 }),
262 );
263 }
264 return Cause.done();
265 }
266 return pull.pipe(
267 Effect.map((chunks) => {
268 buffer = concatBytes([buffer, ...chunks]);
269 }),
270 Pull.catchDone(() =>
271 Effect.sync(() => {
272 upstreamDone = true;
273 }),
274 ),
275 Effect.flatMap(() => loop),
276 );
277 });
278
279 return loop;
280 }),
281 );