@qlairoslabs/acp-client 0.1.5 → 0.3.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/README.md +209 -4
- package/package.json +2 -1
- package/src/activity.ts +513 -0
- package/src/agent-session.ts +244 -2
- package/src/capabilities.ts +30 -3
- package/src/cli/index.ts +21 -3
- package/src/client.ts +93 -8
- package/src/controller.ts +7 -0
- package/src/fs-access.ts +38 -0
- package/src/index.ts +41 -1
- package/src/repl/repl.ts +11 -1
- package/src/terminals.ts +273 -0
- package/src/transcript.ts +228 -16
- package/src/transport/acp-transport.ts +164 -21
- package/src/types.ts +129 -12
- package/src/updates.ts +137 -14
- package/src/wire-log.ts +85 -0
package/src/controller.ts
CHANGED
|
@@ -11,6 +11,7 @@ import type {
|
|
|
11
11
|
PromptHandlers,
|
|
12
12
|
PromptResult,
|
|
13
13
|
SessionListPage,
|
|
14
|
+
WireEntry,
|
|
14
15
|
} from "./types.ts";
|
|
15
16
|
import { NotConnectedError } from "./errors.ts";
|
|
16
17
|
|
|
@@ -38,7 +39,11 @@ export interface AgentControllerConfig {
|
|
|
38
39
|
mcpServers?: schema.McpServer[];
|
|
39
40
|
defaultPermission?: "approve" | "cancel";
|
|
40
41
|
clientInfo?: AcpClientConfig["clientInfo"];
|
|
42
|
+
/** What we let the agent do through us (terminals, filesystem). All on by default. */
|
|
43
|
+
clientCapabilities?: AcpClientConfig["clientCapabilities"];
|
|
41
44
|
logger?: Logger;
|
|
45
|
+
/** Raw protocol traffic for debugging — see `AcpClientConfig.wire`. */
|
|
46
|
+
wire?: (entry: WireEntry) => void;
|
|
42
47
|
}
|
|
43
48
|
|
|
44
49
|
export type ControllerCommandId =
|
|
@@ -369,7 +374,9 @@ export class AgentController implements AgentClient {
|
|
|
369
374
|
sessionId,
|
|
370
375
|
defaultPermission: this.config.defaultPermission,
|
|
371
376
|
clientInfo: this.config.clientInfo,
|
|
377
|
+
clientCapabilities: this.config.clientCapabilities,
|
|
372
378
|
logger: this.config.logger,
|
|
379
|
+
wire: this.config.wire,
|
|
373
380
|
});
|
|
374
381
|
// connect() is fatal (no connection = nothing to do). startSession() is NOT: an
|
|
375
382
|
// unauthenticated agent may refuse session/new, but we keep the connection up so the
|
package/src/fs-access.ts
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
// Client-side filesystem access (ACP `fs/read_text_file`, `fs/write_text_file`).
|
|
2
|
+
//
|
|
3
|
+
// We advertise the fs capabilities, so these must actually work — previously the
|
|
4
|
+
// transport answered every read with `{content: ""}` and silently discarded writes,
|
|
5
|
+
// which reads to an agent as "the file is empty" / "the write succeeded".
|
|
6
|
+
|
|
7
|
+
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
8
|
+
import { dirname } from "node:path";
|
|
9
|
+
|
|
10
|
+
export interface ReadTextFileParams {
|
|
11
|
+
path: string;
|
|
12
|
+
/** 1-based line to start from. */
|
|
13
|
+
line?: number | null;
|
|
14
|
+
/** Maximum number of lines to return. */
|
|
15
|
+
limit?: number | null;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface WriteTextFileParams {
|
|
19
|
+
path: string;
|
|
20
|
+
content: string;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Read a file, honouring the protocol's optional line window. */
|
|
24
|
+
export async function readTextFile(params: ReadTextFileParams): Promise<string> {
|
|
25
|
+
const content = await readFile(params.path, "utf8");
|
|
26
|
+
if (params.line == null && params.limit == null) return content;
|
|
27
|
+
|
|
28
|
+
const lines = content.split("\n");
|
|
29
|
+
const start = Math.max((params.line ?? 1) - 1, 0);
|
|
30
|
+
const end = params.limit != null ? start + Math.max(params.limit, 0) : lines.length;
|
|
31
|
+
return lines.slice(start, end).join("\n");
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Write a file, creating parent directories as needed. */
|
|
35
|
+
export async function writeTextFile(params: WriteTextFileParams): Promise<void> {
|
|
36
|
+
await mkdir(dirname(params.path), { recursive: true });
|
|
37
|
+
await writeFile(params.path, params.content, "utf8");
|
|
38
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -29,7 +29,7 @@ export type {
|
|
|
29
29
|
} from "./controller.ts";
|
|
30
30
|
|
|
31
31
|
export { AgentSession } from "./agent-session.ts";
|
|
32
|
-
export type { AgentSessionConfig } from "./agent-session.ts";
|
|
32
|
+
export type { AgentSessionConfig, TranscriptActivityConfig } from "./agent-session.ts";
|
|
33
33
|
|
|
34
34
|
export type {
|
|
35
35
|
AgentClient,
|
|
@@ -41,12 +41,40 @@ export type {
|
|
|
41
41
|
export { ADAPTERS, buildSpawnCommand } from "./adapters.ts";
|
|
42
42
|
export type { Adapter, AdapterPreset } from "./adapters.ts";
|
|
43
43
|
|
|
44
|
+
export { buildClientCapabilities, CLIENT_CAPABILITIES } from "./capabilities.ts";
|
|
44
45
|
export type {
|
|
45
46
|
Capabilities,
|
|
46
47
|
ClientCapabilities,
|
|
48
|
+
ClientCapabilityConfig,
|
|
47
49
|
AgentCapabilities,
|
|
48
50
|
AuthMethod,
|
|
49
51
|
} from "./capabilities.ts";
|
|
52
|
+
|
|
53
|
+
export { TerminalRegistry, UnknownTerminalError } from "./terminals.ts";
|
|
54
|
+
export type {
|
|
55
|
+
CreateTerminalParams,
|
|
56
|
+
TerminalOutput,
|
|
57
|
+
TerminalRegistryOptions,
|
|
58
|
+
} from "./terminals.ts";
|
|
59
|
+
|
|
60
|
+
export { extractChunkText, toActivityEvent } from "./updates.ts";
|
|
61
|
+
|
|
62
|
+
export {
|
|
63
|
+
ActivityAggregator,
|
|
64
|
+
foldRecords,
|
|
65
|
+
foldFrame,
|
|
66
|
+
wireFrames,
|
|
67
|
+
isActivityDelta,
|
|
68
|
+
} from "./activity.ts";
|
|
69
|
+
export type {
|
|
70
|
+
ActivityAggregatorOptions,
|
|
71
|
+
ActivityDelta,
|
|
72
|
+
ActivityFrame,
|
|
73
|
+
ActivitySnapshot,
|
|
74
|
+
AggregatedRecord,
|
|
75
|
+
ApplyResult,
|
|
76
|
+
EmitReason,
|
|
77
|
+
} from "./activity.ts";
|
|
50
78
|
export type {
|
|
51
79
|
ConfigOption,
|
|
52
80
|
ConfigOptions,
|
|
@@ -63,8 +91,10 @@ export type { MergedSession, SessionInput } from "./session-manager.ts";
|
|
|
63
91
|
|
|
64
92
|
export {
|
|
65
93
|
appendTranscriptLine,
|
|
94
|
+
readActivityRecords,
|
|
66
95
|
readTranscript,
|
|
67
96
|
readTranscriptLines,
|
|
97
|
+
toActivityRecord,
|
|
68
98
|
} from "./transcript.ts";
|
|
69
99
|
export type {
|
|
70
100
|
ReadTranscriptOptions,
|
|
@@ -80,6 +110,9 @@ export type {
|
|
|
80
110
|
|
|
81
111
|
export { ProcessCrashError, NotConnectedError, TimeoutError } from "./errors.ts";
|
|
82
112
|
|
|
113
|
+
export { createWireLog } from "./wire-log.ts";
|
|
114
|
+
export type { WireLogOptions } from "./wire-log.ts";
|
|
115
|
+
|
|
83
116
|
export { noopLogger, createConsoleLogger } from "./logger.ts";
|
|
84
117
|
export type { Logger, LogLevel, ConsoleLoggerOptions } from "./logger.ts";
|
|
85
118
|
|
|
@@ -87,6 +120,12 @@ export type {
|
|
|
87
120
|
PromptResult,
|
|
88
121
|
PromptHandlers,
|
|
89
122
|
ActivityEvent,
|
|
123
|
+
ToolActivity,
|
|
124
|
+
ToolUpdateActivity,
|
|
125
|
+
ToolContent,
|
|
126
|
+
ToolLocation,
|
|
127
|
+
TerminalExitStatus,
|
|
128
|
+
ContentBlock,
|
|
90
129
|
PlanEntry,
|
|
91
130
|
PermissionRequest,
|
|
92
131
|
PermissionOutcome,
|
|
@@ -95,4 +134,5 @@ export type {
|
|
|
95
134
|
SessionListEntry,
|
|
96
135
|
SessionListPage,
|
|
97
136
|
AgentCommand,
|
|
137
|
+
WireEntry,
|
|
98
138
|
} from "./types.ts";
|
package/src/repl/repl.ts
CHANGED
|
@@ -304,9 +304,19 @@ function activityMarker(e: ActivityEvent): string | null {
|
|
|
304
304
|
return "thinking";
|
|
305
305
|
case "tool":
|
|
306
306
|
return `tool:${e.title ?? e.toolKind}`;
|
|
307
|
+
case "tool_update":
|
|
308
|
+
// Only the terminal states are worth a marker; progress ticks are too noisy.
|
|
309
|
+
return e.status === "completed" || e.status === "failed"
|
|
310
|
+
? `tool:${e.title ?? e.toolCallId} ${e.status}`
|
|
311
|
+
: null;
|
|
307
312
|
case "plan":
|
|
313
|
+
case "plan_update":
|
|
308
314
|
return "plan";
|
|
315
|
+
case "mode":
|
|
316
|
+
return `mode:${e.modeId}`;
|
|
317
|
+
case "usage":
|
|
318
|
+
return `context:${e.used}/${e.size}`;
|
|
309
319
|
default:
|
|
310
|
-
return null; //
|
|
320
|
+
return null; // bookkeeping updates — nothing for a one-line marker to say
|
|
311
321
|
}
|
|
312
322
|
}
|
package/src/terminals.ts
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
/// <reference types="bun" />
|
|
2
|
+
// Client-side terminals (ACP `terminal/*`). The agent asks US to run a command and then
|
|
3
|
+
// polls for output; the tool call it emits carries only a `terminalId`, so without this
|
|
4
|
+
// the whole execute-tool path produces empty UI.
|
|
5
|
+
//
|
|
6
|
+
// We advertise `terminal` in client capabilities, so per spec we MUST implement all five
|
|
7
|
+
// methods. See https://agentclientprotocol.com/protocol/terminals.
|
|
8
|
+
|
|
9
|
+
import type { Logger } from "./logger.ts";
|
|
10
|
+
import { noopLogger } from "./logger.ts";
|
|
11
|
+
import type { TerminalExitStatus } from "./types.ts";
|
|
12
|
+
|
|
13
|
+
export interface CreateTerminalParams {
|
|
14
|
+
command: string;
|
|
15
|
+
args?: string[];
|
|
16
|
+
cwd?: string | null;
|
|
17
|
+
env?: Array<{ name: string; value: string }>;
|
|
18
|
+
/** Bytes of output to retain; older output is dropped from the FRONT. */
|
|
19
|
+
outputByteLimit?: number | null;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface TerminalOutput {
|
|
23
|
+
output: string;
|
|
24
|
+
truncated: boolean;
|
|
25
|
+
exitStatus: TerminalExitStatus | null;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface TerminalRegistryOptions {
|
|
29
|
+
/** Fallback cwd when the agent doesn't specify one. */
|
|
30
|
+
cwd?: string;
|
|
31
|
+
/** Extra env for every terminal, merged over process.env. */
|
|
32
|
+
env?: Record<string, string>;
|
|
33
|
+
logger?: Logger;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Thrown when the agent references a terminal that was released or never existed. */
|
|
37
|
+
export class UnknownTerminalError extends Error {
|
|
38
|
+
constructor(terminalId: string) {
|
|
39
|
+
super(`unknown terminalId: ${terminalId}`);
|
|
40
|
+
this.name = "UnknownTerminalError";
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
interface Chunk {
|
|
45
|
+
text: string;
|
|
46
|
+
bytes: number;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
interface Entry {
|
|
50
|
+
id: string;
|
|
51
|
+
proc: ReturnType<typeof Bun.spawn>;
|
|
52
|
+
chunks: Chunk[];
|
|
53
|
+
/** Memoized `chunks.join("")`; nulled on every write. */
|
|
54
|
+
joined: string | null;
|
|
55
|
+
totalBytes: number;
|
|
56
|
+
limit: number | null;
|
|
57
|
+
truncated: boolean;
|
|
58
|
+
exitStatus: TerminalExitStatus | null;
|
|
59
|
+
exited: Promise<TerminalExitStatus>;
|
|
60
|
+
// Structural: Bun's and node:stream/web's reader types differ, and we only cancel.
|
|
61
|
+
readers: Array<{ cancel(): Promise<unknown> }>;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* How long to keep draining output after the process exits. A killed shell can leave a
|
|
66
|
+
* grandchild holding the pipe, so EOF may never come — waiting on it unboundedly would
|
|
67
|
+
* hang `terminal/wait_for_exit` and with it the agent's whole turn.
|
|
68
|
+
*/
|
|
69
|
+
const DRAIN_GRACE_MS = 250;
|
|
70
|
+
|
|
71
|
+
export class TerminalRegistry {
|
|
72
|
+
private readonly terminals = new Map<string, Entry>();
|
|
73
|
+
private seq = 0;
|
|
74
|
+
private readonly log: Logger;
|
|
75
|
+
|
|
76
|
+
constructor(private readonly options: TerminalRegistryOptions = {}) {
|
|
77
|
+
this.log = options.logger ?? noopLogger;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Spawn a command and return its terminal id. Output accumulates until released. */
|
|
81
|
+
create(params: CreateTerminalParams): string {
|
|
82
|
+
const id = `term-${++this.seq}`;
|
|
83
|
+
const env: Record<string, string> = {
|
|
84
|
+
...(process.env as Record<string, string>),
|
|
85
|
+
...(this.options.env ?? {}),
|
|
86
|
+
};
|
|
87
|
+
for (const v of params.env ?? []) env[v.name] = v.value;
|
|
88
|
+
|
|
89
|
+
const proc = Bun.spawn([params.command, ...(params.args ?? [])], {
|
|
90
|
+
cwd: params.cwd ?? this.options.cwd,
|
|
91
|
+
env,
|
|
92
|
+
stdin: "ignore",
|
|
93
|
+
stdout: "pipe",
|
|
94
|
+
stderr: "pipe",
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
const entry: Entry = {
|
|
98
|
+
id,
|
|
99
|
+
proc,
|
|
100
|
+
chunks: [],
|
|
101
|
+
joined: null,
|
|
102
|
+
totalBytes: 0,
|
|
103
|
+
limit: params.outputByteLimit ?? null,
|
|
104
|
+
truncated: false,
|
|
105
|
+
exitStatus: null,
|
|
106
|
+
exited: Promise.resolve({ exitCode: null, signal: null }),
|
|
107
|
+
readers: [],
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
// stdout and stderr are interleaved in arrival order — that's what a terminal is.
|
|
111
|
+
const pumps = [
|
|
112
|
+
this.pump(entry, proc.stdout as ReadableStream<Uint8Array>),
|
|
113
|
+
this.pump(entry, proc.stderr as ReadableStream<Uint8Array>),
|
|
114
|
+
];
|
|
115
|
+
|
|
116
|
+
entry.exited = (async () => {
|
|
117
|
+
const code = await proc.exited;
|
|
118
|
+
// Drain whatever was still buffered before reporting the exit status, so a caller
|
|
119
|
+
// that waits for exit and then reads output never races the last few bytes.
|
|
120
|
+
await Promise.race([Promise.allSettled(pumps), Bun.sleep(DRAIN_GRACE_MS)]);
|
|
121
|
+
const status: TerminalExitStatus = {
|
|
122
|
+
exitCode: proc.signalCode ? null : (code ?? null),
|
|
123
|
+
signal: proc.signalCode ?? null,
|
|
124
|
+
};
|
|
125
|
+
entry.exitStatus = status;
|
|
126
|
+
this.log.debug("terminal_exit", { terminalId: id, ...status });
|
|
127
|
+
return status;
|
|
128
|
+
})();
|
|
129
|
+
void entry.exited.catch(() => {});
|
|
130
|
+
|
|
131
|
+
this.terminals.set(id, entry);
|
|
132
|
+
this.log.debug("terminal_create", { terminalId: id, command: params.command, args: params.args });
|
|
133
|
+
return id;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Current output and exit status. Fully synchronous — it reads a buffer the background
|
|
138
|
+
* pumps fill, and never waits on the process. That matters beyond convenience: this is
|
|
139
|
+
* called while dispatching session updates, so an await here would let one wedged
|
|
140
|
+
* command stall every subsequent update on the connection.
|
|
141
|
+
*/
|
|
142
|
+
output(terminalId: string): TerminalOutput {
|
|
143
|
+
const entry = this.require(terminalId);
|
|
144
|
+
// Joining is O(buffered bytes) and a live terminal is read once per update that
|
|
145
|
+
// references it, so hold the result until the next write.
|
|
146
|
+
entry.joined ??= entry.chunks.map((c) => c.text).join("");
|
|
147
|
+
return {
|
|
148
|
+
output: entry.joined,
|
|
149
|
+
truncated: entry.truncated,
|
|
150
|
+
exitStatus: entry.exitStatus,
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Resolve once the command exits. */
|
|
155
|
+
waitForExit(terminalId: string): Promise<TerminalExitStatus> {
|
|
156
|
+
return this.require(terminalId).exited;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Kill the command but keep the id valid, so output stays readable. */
|
|
160
|
+
kill(terminalId: string): void {
|
|
161
|
+
const entry = this.require(terminalId);
|
|
162
|
+
try {
|
|
163
|
+
entry.proc.kill("SIGKILL");
|
|
164
|
+
} catch {
|
|
165
|
+
/* already exited */
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** Kill and forget. The id becomes invalid for every other method. */
|
|
170
|
+
release(terminalId: string): void {
|
|
171
|
+
const entry = this.terminals.get(terminalId);
|
|
172
|
+
if (!entry) return;
|
|
173
|
+
this.terminals.delete(terminalId);
|
|
174
|
+
try {
|
|
175
|
+
entry.proc.kill("SIGKILL");
|
|
176
|
+
} catch {
|
|
177
|
+
/* already exited */
|
|
178
|
+
}
|
|
179
|
+
// Cancel explicitly: a surviving grandchild can hold the pipes open indefinitely.
|
|
180
|
+
for (const reader of entry.readers) void reader.cancel().catch(() => {});
|
|
181
|
+
entry.readers = [];
|
|
182
|
+
this.log.debug("terminal_release", { terminalId });
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** Tear everything down (client stop). */
|
|
186
|
+
releaseAll(): void {
|
|
187
|
+
for (const id of [...this.terminals.keys()]) this.release(id);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** True while the id is still ours to read — used to enrich tool-call content. */
|
|
191
|
+
has(terminalId: string): boolean {
|
|
192
|
+
return this.terminals.has(terminalId);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
private require(terminalId: string): Entry {
|
|
196
|
+
const entry = this.terminals.get(terminalId);
|
|
197
|
+
if (!entry) throw new UnknownTerminalError(terminalId);
|
|
198
|
+
return entry;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
private async pump(entry: Entry, stream: ReadableStream<Uint8Array> | null): Promise<void> {
|
|
202
|
+
if (!stream) return;
|
|
203
|
+
const reader = stream.getReader();
|
|
204
|
+
entry.readers.push(reader);
|
|
205
|
+
const dec = new TextDecoder();
|
|
206
|
+
try {
|
|
207
|
+
for (;;) {
|
|
208
|
+
const { value, done } = await reader.read();
|
|
209
|
+
if (done) break;
|
|
210
|
+
this.append(entry, dec.decode(value, { stream: true }));
|
|
211
|
+
}
|
|
212
|
+
const tail = dec.decode();
|
|
213
|
+
if (tail) this.append(entry, tail);
|
|
214
|
+
} catch (err) {
|
|
215
|
+
this.log.debug("terminal_read_failed", { terminalId: entry.id, error: String(err) });
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
private append(entry: Entry, text: string): void {
|
|
220
|
+
if (!text) return;
|
|
221
|
+
entry.joined = null;
|
|
222
|
+
entry.chunks.push({ text, bytes: Buffer.byteLength(text, "utf8") });
|
|
223
|
+
entry.totalBytes += Buffer.byteLength(text, "utf8");
|
|
224
|
+
this.trim(entry);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* Enforce outputByteLimit by dropping from the FRONT, whole chunks first, then a
|
|
229
|
+
* character-boundary cut inside the oldest surviving chunk (per spec: truncation must
|
|
230
|
+
* not split a character, even if that leaves us slightly under the limit).
|
|
231
|
+
*/
|
|
232
|
+
private trim(entry: Entry): void {
|
|
233
|
+
const limit = entry.limit;
|
|
234
|
+
if (limit == null || limit < 0) return;
|
|
235
|
+
while (entry.totalBytes > limit && entry.chunks.length > 0) {
|
|
236
|
+
const first = entry.chunks[0]!;
|
|
237
|
+
if (entry.totalBytes - first.bytes >= limit) {
|
|
238
|
+
entry.chunks.shift();
|
|
239
|
+
entry.totalBytes -= first.bytes;
|
|
240
|
+
entry.truncated = true;
|
|
241
|
+
continue;
|
|
242
|
+
}
|
|
243
|
+
const drop = entry.totalBytes - limit;
|
|
244
|
+
const cut = charBoundaryCut(first.text, drop);
|
|
245
|
+
const kept = first.text.slice(cut);
|
|
246
|
+
const keptBytes = Buffer.byteLength(kept, "utf8");
|
|
247
|
+
entry.totalBytes -= first.bytes - keptBytes;
|
|
248
|
+
entry.truncated = true;
|
|
249
|
+
if (kept) {
|
|
250
|
+
entry.chunks[0] = { text: kept, bytes: keptBytes };
|
|
251
|
+
} else {
|
|
252
|
+
entry.chunks.shift();
|
|
253
|
+
}
|
|
254
|
+
break;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* Smallest index such that dropping `text[0..index)` sheds at least `dropBytes` bytes,
|
|
261
|
+
* landing on a code-point boundary.
|
|
262
|
+
*/
|
|
263
|
+
function charBoundaryCut(text: string, dropBytes: number): number {
|
|
264
|
+
let shed = 0;
|
|
265
|
+
let i = 0;
|
|
266
|
+
while (i < text.length && shed < dropBytes) {
|
|
267
|
+
const code = text.codePointAt(i)!;
|
|
268
|
+
const width = code > 0xffff ? 2 : 1;
|
|
269
|
+
shed += Buffer.byteLength(text.slice(i, i + width), "utf8");
|
|
270
|
+
i += width;
|
|
271
|
+
}
|
|
272
|
+
return i;
|
|
273
|
+
}
|