@planu/cli 8.8.0 → 8.9.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.
@@ -1,190 +1,7 @@
1
1
  import { createHash } from 'node:crypto';
2
- import { constants } from 'node:fs';
3
- import { lstat, open, realpath } from 'node:fs/promises';
4
- import { join, relative, resolve, sep } from 'node:path';
5
- function fail(cause) {
6
- return { ok: false, cause };
7
- }
8
- function sameIdentity(a, b) {
9
- return (a.dev === b.dev && a.ino === b.ino && a.mode === b.mode && a.uid === b.uid && a.gid === b.gid);
10
- }
11
- function sameFile(a, b) {
12
- return (sameIdentity(a, b) &&
13
- a.nlink === b.nlink &&
14
- a.size === b.size &&
15
- a.mtimeNs === b.mtimeNs &&
16
- a.ctimeNs === b.ctimeNs);
17
- }
18
- function safeFile(stat) {
19
- return stat.isFile() && !stat.isSymbolicLink() && stat.nlink === 1n;
20
- }
21
- function errorCause(error, observed) {
22
- const code = typeof error === 'object' && error !== null && 'code' in error ? error.code : undefined;
23
- switch (code) {
24
- case 'ENOENT':
25
- return observed ? 'unstable' : 'not_found';
26
- case 'EACCES':
27
- case 'EPERM':
28
- return 'access_denied';
29
- case 'ELOOP':
30
- case 'ENOTDIR':
31
- return 'unsafe_path';
32
- default:
33
- return 'read_failed';
34
- }
35
- }
36
- class HostSkillReader {
37
- lexicalRoot;
38
- local;
39
- maxBytes;
40
- directories = [];
41
- canonicalRoot;
42
- observedTarget = false;
43
- handle;
44
- constructor(lexicalRoot, local, maxBytes) {
45
- this.lexicalRoot = lexicalRoot;
46
- this.local = local;
47
- this.maxBytes = maxBytes;
48
- }
49
- async run() {
50
- let result;
51
- try {
52
- result = await this.captureAndRead();
53
- }
54
- catch (error) {
55
- result = await this.failure(error);
56
- }
57
- if (this.handle) {
58
- try {
59
- await this.handle.close();
60
- }
61
- catch {
62
- result = fail('read_failed');
63
- }
64
- }
65
- return result;
66
- }
67
- async failure(error) {
68
- const cause = errorCause(error, this.observedTarget);
69
- try {
70
- if (!(await this.recheckDirectories())) {
71
- return fail('unstable');
72
- }
73
- return fail(cause === 'not_found' && this.directories.length === 0 ? 'unsafe_path' : cause);
74
- }
75
- catch {
76
- return fail('unstable');
77
- }
78
- }
79
- async recheckDirectories() {
80
- if (this.canonicalRoot !== undefined &&
81
- (await realpath(this.lexicalRoot)) !== this.canonicalRoot) {
82
- return false;
83
- }
84
- for (const directory of this.directories) {
85
- const current = await lstat(directory.path, { bigint: true });
86
- if (!current.isDirectory() ||
87
- current.isSymbolicLink() ||
88
- !sameIdentity(directory.stat, current)) {
89
- return false;
90
- }
91
- }
92
- return true;
93
- }
94
- async capturePath() {
95
- const root = await realpath(this.lexicalRoot);
96
- this.canonicalRoot = root;
97
- let current = root;
98
- for (const component of this.local.split(sep)) {
99
- const stat = await lstat(current, { bigint: true });
100
- if (!stat.isDirectory() || stat.isSymbolicLink()) {
101
- return undefined;
102
- }
103
- this.directories.push({ path: current, stat });
104
- current = join(current, component);
105
- }
106
- return current;
107
- }
108
- async captureAndRead() {
109
- const target = await this.capturePath();
110
- if (target === undefined) {
111
- return fail('unsafe_path');
112
- }
113
- const before = await lstat(target, { bigint: true });
114
- this.observedTarget = true;
115
- if (!safeFile(before)) {
116
- return fail('unsafe_path');
117
- }
118
- if (before.size > BigInt(this.maxBytes)) {
119
- return fail('over_limit');
120
- }
121
- this.handle = await open(target, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
122
- const opened = await this.handle.stat({ bigint: true });
123
- if (!safeFile(opened)) {
124
- return fail('unsafe_path');
125
- }
126
- if (!sameFile(before, opened)) {
127
- return fail('unstable');
128
- }
129
- if (opened.size > BigInt(this.maxBytes)) {
130
- return fail('over_limit');
131
- }
132
- if (!(await this.recheckDirectories()) || (await realpath(target)) !== target) {
133
- return fail('unstable');
134
- }
135
- const revalidated = await lstat(target, { bigint: true });
136
- if (!safeFile(revalidated) || !sameFile(opened, revalidated)) {
137
- return fail('unstable');
138
- }
139
- return this.readDescriptor(this.handle, target, opened);
140
- }
141
- async readDescriptor(handle, target, opened) {
142
- const bytes = Buffer.alloc(this.maxBytes);
143
- let total = 0;
144
- while (total < this.maxBytes) {
145
- const { bytesRead } = await handle.read(bytes, total, this.maxBytes - total, total);
146
- if (bytesRead === 0) {
147
- break;
148
- }
149
- total += bytesRead;
150
- }
151
- const after = await handle.stat({ bigint: true });
152
- const final = await lstat(target, { bigint: true });
153
- if (after.size > BigInt(this.maxBytes) || final.size > BigInt(this.maxBytes)) {
154
- return fail('over_limit');
155
- }
156
- if (!sameFile(opened, after) ||
157
- !sameFile(after, final) ||
158
- after.size !== BigInt(total) ||
159
- !safeFile(final) ||
160
- !(await this.recheckDirectories()) ||
161
- (await realpath(target)) !== target) {
162
- return fail('unstable');
163
- }
164
- try {
165
- return {
166
- ok: true,
167
- text: new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes.subarray(0, total)),
168
- };
169
- }
170
- catch {
171
- return fail('invalid_content');
172
- }
173
- }
174
- }
175
- /** Strict bounded reader for host diagnostics; legacy reader semantics remain unchanged. */
176
- export function readTextInsideWorkspaceDetailed(workspaceRoot, absolutePath, options) {
177
- const { maxBytes } = options;
178
- if (!Number.isSafeInteger(maxBytes) || maxBytes < 0 || maxBytes > 65_536) {
179
- return Promise.resolve(fail('read_failed'));
180
- }
181
- const root = resolve(workspaceRoot);
182
- const local = relative(root, resolve(absolutePath));
183
- if (!local || local === '..' || local.startsWith(`..${sep}`) || resolve(local) === local) {
184
- return Promise.resolve(fail('unsafe_path'));
185
- }
186
- return new HostSkillReader(root, local, maxBytes).run();
187
- }
2
+ import { join, sep } from 'node:path';
3
+ import * as root from './workspace-root.js';
4
+ export { readTextInsideWorkspaceDetailed } from './workspace-root.js';
188
5
  function digest(text) {
189
6
  return createHash('sha256').update(text, 'utf8').digest('hex');
190
7
  }
@@ -196,7 +13,10 @@ async function scanHostSkills(workspaceRoot, targets, expected, readTarget) {
196
13
  const reference = expected.get(target.slug);
197
14
  const read = await readTarget(workspaceRoot, join(workspaceRoot, target.relative), {
198
15
  maxBytes: 65_536,
199
- }).catch(() => ({ ok: false, cause: 'read_failed' }));
16
+ }).catch(() => ({
17
+ ok: false,
18
+ cause: 'read_failed',
19
+ }));
200
20
  return {
201
21
  ...target,
202
22
  referenceSha256: reference === undefined ? null : digest(reference),
@@ -227,16 +47,14 @@ export async function scanPack(workspaceRoot, templatesRoot, slugs, targetsFor,
227
47
  });
228
48
  const available = sources.every((result) => result.status === 'fulfilled') && expected.size === slugs.length;
229
49
  const targets = slugs.flatMap((slug) => targetsFor(slug).map((targetPath) => ({ slug, relative: targetPath })));
230
- return { available, rows: await scanHostSkills(workspaceRoot, targets, expected, readTarget) };
50
+ const rows = await scanHostSkills(workspaceRoot, targets, expected, readTarget);
51
+ return { available, rows };
231
52
  }
232
53
  export function legacyIssue(row, available) {
233
54
  const fixedPath = row.relative.split(sep).join('/');
234
55
  if (!row.read.ok) {
235
- return {
236
- path: fixedPath,
237
- status: row.read.cause === 'not_found' ? 'missing' : 'unreadable',
238
- cause: row.read.cause,
239
- };
56
+ const status = row.read.cause === 'not_found' ? 'missing' : 'unreadable';
57
+ return { path: fixedPath, status, cause: row.read.cause };
240
58
  }
241
59
  if (available && !row.matches) {
242
60
  return { path: fixedPath, status: 'different', cause: 'content_mismatch' };
@@ -258,16 +76,12 @@ function hostDisposition(row) {
258
76
  : { status: 'different', cause: 'content_mismatch' };
259
77
  }
260
78
  export function diagnosticRow(row, version) {
261
- const host = { '.claude': 'claude', '.cursor': 'cursor', '.agents': 'codex', '.gemini': 'gemini' }[row.relative.split(sep)[0]];
262
- const base = {
263
- host,
264
- role: row.slug,
265
- path: row.relative.split(sep).join('/'),
266
- referenceVersion: version,
267
- referenceSha256: row.referenceSha256,
268
- installedSha256: row.installedSha256,
269
- installedVersion: 'unverified',
270
- };
79
+ const host = {
80
+ '.claude': 'claude',
81
+ '.cursor': 'cursor',
82
+ '.agents': 'codex',
83
+ '.gemini': 'gemini',
84
+ }[row.relative.split(sep)[0]];
271
85
  const disposition = hostDisposition(row);
272
86
  const proposedAction = {
273
87
  match: 'none',
@@ -276,33 +90,229 @@ export function diagnosticRow(row, version) {
276
90
  unreadable: 'inspect_path',
277
91
  reference_unavailable: 'inspect_installation',
278
92
  };
279
- return { ...base, ...disposition, proposedAction: proposedAction[disposition.status] };
93
+ return {
94
+ host,
95
+ role: row.slug,
96
+ path: row.relative.split(sep).join('/'),
97
+ referenceVersion: version,
98
+ referenceSha256: row.referenceSha256,
99
+ installedSha256: row.installedSha256,
100
+ installedVersion: 'unverified',
101
+ ...disposition,
102
+ proposedAction: proposedAction[disposition.status],
103
+ };
280
104
  }
281
- export function clientInfo(value) {
282
- if (value === undefined || value === null) {
283
- return { client: null, clientMetadataCause: 'unavailable' };
105
+ export { clientInfo } from './client-workspace.js';
106
+ function appendSegment(segments, position, text, endsLine) {
107
+ const last = segments.at(-1);
108
+ if (last?.line === position.line) {
109
+ return [...segments.slice(0, -1), { ...last, text: last.text + text, endsLine }];
284
110
  }
285
- if (typeof value !== 'object' ||
286
- !('name' in value) ||
287
- !('version' in value) ||
288
- typeof value.name !== 'string' ||
289
- typeof value.version !== 'string' ||
290
- Array.from(value.name + value.version).some((char) => {
291
- const code = char.codePointAt(0) ?? 0;
292
- return code < 32 || (code >= 127 && code <= 159);
293
- })) {
294
- return { client: null, clientMetadataCause: 'invalid' };
111
+ return [
112
+ ...segments,
113
+ { line: position.line, lineOffsetBytes: position.lineOffsetBytes, text, endsLine },
114
+ ];
115
+ }
116
+ function scalarWidth(lead) {
117
+ return lead <= 0x7f ? 1 : lead < 0xc2 || lead > 0xf4 ? 0 : lead < 0xe0 ? 2 : lead < 0xf0 ? 3 : 4;
118
+ }
119
+ function decodeScalar(decoder, view, index, bytes) {
120
+ try {
121
+ return decoder.decode(view.subarray(index, index + bytes));
295
122
  }
296
- if (Buffer.byteLength(value.name) > 128 || Buffer.byteLength(value.version) > 128) {
297
- return { client: null, clientMetadataCause: 'over_limit' };
123
+ catch {
124
+ return null;
298
125
  }
126
+ }
127
+ function advance(position, text, bytes, endsRange) {
299
128
  return {
300
- client: {
301
- name: value.name,
302
- version: value.version,
303
- source: 'initialize',
304
- provenance: 'client_reported',
305
- },
129
+ consumedBytes: position.consumedBytes + bytes,
130
+ line: position.line + (text === '\n' && !endsRange ? 1 : 0),
131
+ lineOffsetBytes: text === '\n' ? 0 : position.lineOffsetBytes + bytes,
306
132
  };
307
133
  }
134
+ class BoundedSource {
135
+ context;
136
+ input;
137
+ position;
138
+ codec;
139
+ request;
140
+ view = new Uint8Array(0);
141
+ index = 0;
142
+ fetched = 0;
143
+ calls = 0;
144
+ completed = 0;
145
+ segments = [];
146
+ decoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
147
+ initial;
148
+ constructor(context, input, position, codec, request) {
149
+ this.context = context;
150
+ this.input = input;
151
+ this.position = position;
152
+ this.codec = codec;
153
+ this.request = request;
154
+ this.initial = position.consumedBytes;
155
+ }
156
+ async fill() {
157
+ const position = this.initial + this.fetched;
158
+ if (position >= this.context.snapshot.size || this.calls >= 64 || this.fetched >= 65_536) {
159
+ return false;
160
+ }
161
+ const carry = this.view.subarray(this.index);
162
+ const part = await this.context.read(position, Math.min(4096, 65_536 - this.fetched));
163
+ this.calls++;
164
+ this.fetched += part.byteLength;
165
+ this.view = new Uint8Array(part.buffer, part.byteOffset - carry.length, carry.length + part.length);
166
+ this.index = 0;
167
+ return true;
168
+ }
169
+ async scalar() {
170
+ if (this.index === this.view.length && !(await this.fill())) {
171
+ return 'work';
172
+ }
173
+ const bytes = scalarWidth(this.view[this.index] ?? 0x80);
174
+ if (!bytes) {
175
+ return 'invalid';
176
+ }
177
+ while (this.view.length - this.index < bytes) {
178
+ if (!(await this.fill())) {
179
+ return this.initial + this.fetched === this.context.snapshot.size ? 'invalid' : 'work';
180
+ }
181
+ }
182
+ const text = decodeScalar(this.decoder, this.view, this.index, bytes);
183
+ return text === null ? 'invalid' : { text, bytes };
184
+ }
185
+ needsKnownScalar(bytes) {
186
+ if (this.initial + this.fetched === this.context.snapshot.size ||
187
+ (this.calls < 64 && this.fetched < 65_536)) {
188
+ return false;
189
+ }
190
+ const available = this.view.length - this.index - bytes;
191
+ return available === 0 || available < scalarWidth(this.view[this.index + bytes] ?? 0x80);
192
+ }
193
+ page(position, segments, continuation) {
194
+ const snapshot = this.context.snapshot;
195
+ const payload = [
196
+ 'planu.read-cursor.v1',
197
+ 'source',
198
+ snapshot.rootIdentitySha256,
199
+ this.request,
200
+ snapshot.snapshotSha256,
201
+ position.consumedBytes,
202
+ position.line,
203
+ position.lineOffsetBytes,
204
+ ];
205
+ return {
206
+ version: 1,
207
+ snapshotSha256: snapshot.snapshotSha256,
208
+ requested: { startLine: this.input.start_line, endLine: this.input.end_line },
209
+ phase: continuation === null
210
+ ? 'complete'
211
+ : position.line < this.input.start_line
212
+ ? 'seeking'
213
+ : 'reading',
214
+ segments,
215
+ reachedEof: position.consumedBytes === snapshot.size,
216
+ continuation,
217
+ nextCursor: continuation === null ? null : this.codec.encode(payload),
218
+ };
219
+ }
220
+ fits(page) {
221
+ return Buffer.byteLength(JSON.stringify({ success: true, data: { sourcePage: page } })) <= 8192;
222
+ }
223
+ finish(continuation) {
224
+ if (continuation !== null && this.position.consumedBytes === this.initial) {
225
+ return root.failure('slice_response_too_large');
226
+ }
227
+ const sourcePage = this.page(this.position, this.segments, continuation);
228
+ return this.fits(sourcePage)
229
+ ? { success: true, data: { sourcePage } }
230
+ : root.failure('slice_response_too_large');
231
+ }
232
+ step(text, bytes, probeOnly) {
233
+ const selected = this.position.line >= this.input.start_line;
234
+ const atEof = this.position.consumedBytes + bytes === this.context.snapshot.size;
235
+ const endsLine = text === '\n' || atEof;
236
+ const finished = endsLine && this.position.line === this.input.end_line;
237
+ const next = advance(this.position, text, bytes, finished || atEof);
238
+ if (!selected) {
239
+ if (probeOnly) {
240
+ return this.finish('work_limit');
241
+ }
242
+ this.index += bytes;
243
+ this.position = next;
244
+ return atEof ? root.failure('slice_range_unavailable') : null;
245
+ }
246
+ const done = finished || atEof;
247
+ const segments = appendSegment(this.segments, this.position, text, endsLine);
248
+ if (!this.fits(this.page(next, segments, done ? null : 'response_limit'))) {
249
+ return this.finish('response_limit');
250
+ }
251
+ if (this.completed >= 200) {
252
+ return this.finish('line_limit');
253
+ }
254
+ if (probeOnly && !done) {
255
+ return this.finish('work_limit');
256
+ }
257
+ this.index += bytes;
258
+ this.position = next;
259
+ this.segments = segments;
260
+ this.completed += Number(endsLine);
261
+ return done ? this.finish(null) : null;
262
+ }
263
+ async run() {
264
+ for (;;) {
265
+ if (this.position.consumedBytes === this.context.snapshot.size) {
266
+ return root.failure('slice_range_unavailable');
267
+ }
268
+ const scalar = await this.scalar();
269
+ if (scalar === 'invalid') {
270
+ return root.failure('slice_invalid_utf8');
271
+ }
272
+ if (scalar === 'work') {
273
+ return this.finish(this.completed >= 200 ? 'line_limit' : 'work_limit');
274
+ }
275
+ if (this.view.length - this.index - scalar.bytes < 4) {
276
+ await this.fill();
277
+ }
278
+ const probeOnly = this.needsKnownScalar(scalar.bytes);
279
+ const result = this.step(scalar.text, scalar.bytes, probeOnly);
280
+ if (result) {
281
+ return result;
282
+ }
283
+ }
284
+ }
285
+ }
286
+ export async function readBoundedSource(workspaceRoot, input, codec, signal) {
287
+ if (signal?.aborted) {
288
+ return root.failure('cancelled');
289
+ }
290
+ if (input.view !== 'bounded') {
291
+ return root.failure('slice_input_invalid');
292
+ }
293
+ const path = root.slicePath(workspaceRoot, input);
294
+ if (path === null) {
295
+ return root.failure('slice_path_unsafe');
296
+ }
297
+ if (path === undefined) {
298
+ return root.failure('slice_input_invalid');
299
+ }
300
+ const cursor = root.requestCursor(input, path, codec);
301
+ if (cursor === undefined) {
302
+ return root.failure('slice_cursor_invalid');
303
+ }
304
+ const request = root.sourceRequestSha256(path, input.start_line, input.end_line);
305
+ const result = await root.withSourceDescriptor(workspaceRoot, path, async (context) => {
306
+ const position = root.initialPosition(cursor, context.snapshot, input);
307
+ return typeof position === 'string'
308
+ ? root.failure(position)
309
+ : new BoundedSource(context, input, position, codec, request).run();
310
+ }, 'source', signal);
311
+ if (signal?.aborted) {
312
+ return root.failure('cancelled');
313
+ }
314
+ return result.ok
315
+ ? result.value
316
+ : root.failure(root.descriptorFailure(result.cause, cursor !== null));
317
+ }
308
318
  //# sourceMappingURL=host-skill-reader.js.map
@@ -0,0 +1,3 @@
1
+ import type { SourceDescriptorCallback, SourceDescriptorResult } from '../types/completion.js';
2
+ export declare function withSourceDescriptor<T>(workspaceRoot: string, local: string, callback: SourceDescriptorCallback<T>, profile?: 'source' | number, signal?: AbortSignal): Promise<SourceDescriptorResult<T>>;
3
+ //# sourceMappingURL=source-descriptor.d.ts.map