@code-yeongyu/senpi-codemode 2026.11.25 → 2026.11.27
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/CHANGELOG.md +31 -0
- package/README.md +87 -0
- package/package.json +5 -5
- package/src/bridge/reserved.ts +2 -0
- package/src/config/feature-settings.ts +19 -0
- package/src/config/settings.ts +8 -0
- package/src/extension/eval-status-ticker.ts +5 -2
- package/src/extension/runtime-factory.ts +31 -5
- package/src/extension/session-manager.ts +4 -1
- package/src/index.ts +14 -6
- package/src/kernels/js/babel-ast.ts +64 -0
- package/src/kernels/js/binding-patterns.js +166 -0
- package/src/kernels/js/cell-run-context.js +8 -0
- package/src/kernels/js/declaration-extent.js +157 -0
- package/src/kernels/js/erase-types.ts +174 -0
- package/src/kernels/js/js-source-scan.js +181 -0
- package/src/kernels/js/kernel-contract.ts +2 -0
- package/src/kernels/js/last-expression.js +207 -0
- package/src/kernels/js/local-module-loader.ts +7 -2
- package/src/kernels/js/persist-declarations.js +233 -0
- package/src/kernels/js/rewrite-imports.ts +3 -60
- package/src/kernels/js/typescript-cell.ts +39 -0
- package/src/kernels/js/worker-core.js +1 -0
- package/src/kernels/js/worker-indirect-eval.js +4 -860
- package/src/kernels/js/worker-runtime.js +2 -0
- package/src/kernels/js/worker-scope.js +71 -0
- package/src/kernels/js/worker-startup.ts +1 -0
- package/src/prompt/eval-prompt-template.ts +4 -2
- package/src/prompt/eval-prompt.ts +4 -0
- package/src/skill/bun/SKILL.md +1 -0
- package/src/tool/cell-handler.ts +17 -1
- package/src/tool/detached-cell-manager.ts +42 -4
- package/src/tool/detached-notification-queue.ts +48 -7
- package/src/tool/detached-settling.ts +26 -0
- package/src/tool/eval-tool-options.ts +5 -1
- package/src/tool/eval-tool.ts +3 -1
- package/src/tool/js-cell-parse-message.ts +11 -3
- package/src/tool/managed-cell.ts +3 -0
- package/src/tool/run-eval-cell.ts +36 -11
- package/src/tool/scoped-watches.ts +53 -0
- package/src/tool/types.ts +14 -0
- package/src/written-files/model-writes.ts +55 -0
- package/src/written-files/ownership.ts +73 -0
- package/src/written-files/report.ts +63 -0
- package/src/written-files/scan-boundaries.ts +164 -0
- package/src/written-files/source-file.ts +31 -0
- package/src/written-files/tracker.ts +361 -0
- package/src/written-files/window.ts +92 -0
- package/src/written-files/workspace-fs.ts +104 -0
- package/src/written-files/workspace-scan.ts +253 -0
- package/src/written-files/write-hooks.ts +155 -0
- package/src/written-files/written-files.ts +155 -0
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { SCOPE_MONITOR_OP } from "../bridge/reserved.ts";
|
|
2
|
+
import type { AgentExecuteTool } from "../bridges/agent-bridge.ts";
|
|
3
|
+
import type { EvalStatusEvent } from "./types.ts";
|
|
4
|
+
|
|
5
|
+
const ENDED_WATCH_RE = /^No terminal session found with id/u;
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The watches a JS cell's `scope().monitor()` still holds. A stopped or timed-out cell cannot call tools any more, so
|
|
9
|
+
* its scope cannot stop them; the host does, when the cell settles without a result.
|
|
10
|
+
*/
|
|
11
|
+
export class ScopedWatches {
|
|
12
|
+
readonly #held = new Set<string>();
|
|
13
|
+
|
|
14
|
+
/** Consumes a scope-monitor report; false for every other status event. */
|
|
15
|
+
observe(event: EvalStatusEvent): boolean {
|
|
16
|
+
if (event.op !== SCOPE_MONITOR_OP) return false;
|
|
17
|
+
const bashId = event.bashId;
|
|
18
|
+
if (typeof bashId !== "string") return true;
|
|
19
|
+
if (event.held === true) this.#held.add(bashId);
|
|
20
|
+
else this.#held.delete(bashId);
|
|
21
|
+
return true;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
async stopHeld(executeTool: AgentExecuteTool): Promise<readonly string[]> {
|
|
25
|
+
const failures: string[] = [];
|
|
26
|
+
for (const bashId of this.#held) {
|
|
27
|
+
try {
|
|
28
|
+
const result: unknown = await executeTool("kill_bash", { bash_id: bashId });
|
|
29
|
+
const text = resultText(result);
|
|
30
|
+
if (isRecord(result) && result.isError === true && !ENDED_WATCH_RE.test(text)) {
|
|
31
|
+
failures.push(`scoped watch ${bashId} did not stop: ${text}`);
|
|
32
|
+
}
|
|
33
|
+
} catch (error) {
|
|
34
|
+
failures.push(
|
|
35
|
+
`scoped watch ${bashId} did not stop: ${error instanceof Error ? error.message : String(error)}`,
|
|
36
|
+
);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
this.#held.clear();
|
|
40
|
+
return failures;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function isRecord(value: unknown): value is Readonly<Record<string, unknown>> {
|
|
45
|
+
return value !== null && typeof value === "object";
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function resultText(result: unknown): string {
|
|
49
|
+
if (!isRecord(result) || !Array.isArray(result.content)) return "";
|
|
50
|
+
return result.content
|
|
51
|
+
.map((part: unknown) => (isRecord(part) && typeof part.text === "string" ? part.text : ""))
|
|
52
|
+
.join("");
|
|
53
|
+
}
|
package/src/tool/types.ts
CHANGED
|
@@ -339,6 +339,19 @@ export interface EvalListDetails {
|
|
|
339
339
|
|
|
340
340
|
export type EvalResultDetails = EvalToolDetails | EvalListDetails;
|
|
341
341
|
|
|
342
|
+
/** Workspace source files written while the cell ran without a `write` or `edit` call (senpi#7232). */
|
|
343
|
+
export interface EvalWrittenFilesDetails {
|
|
344
|
+
/** Workspace-relative paths, at most the list limit. */
|
|
345
|
+
readonly files: readonly string[];
|
|
346
|
+
/** Every source file written; `files` holds the first of them. */
|
|
347
|
+
readonly total: number;
|
|
348
|
+
/** How many of `files` the write hooks ran for. */
|
|
349
|
+
readonly hooked: number;
|
|
350
|
+
readonly hookFailures?: readonly { readonly path: string; readonly error: string }[];
|
|
351
|
+
/** Why the cell's writes were not checked, when they were not. */
|
|
352
|
+
readonly unchecked?: "git_unavailable" | "over_budget" | "scan_failed" | "check_failed";
|
|
353
|
+
}
|
|
354
|
+
|
|
342
355
|
export interface EvalToolDetails {
|
|
343
356
|
readonly language: EvalLanguage;
|
|
344
357
|
readonly languages?: readonly EvalLanguage[];
|
|
@@ -364,6 +377,7 @@ export interface EvalToolDetails {
|
|
|
364
377
|
readonly memory?: EvalMemoryDetails;
|
|
365
378
|
/** What a kernel death did to this cell's state, when one did. */
|
|
366
379
|
readonly kernelState?: EvalKernelState;
|
|
380
|
+
readonly writtenFiles?: EvalWrittenFilesDetails;
|
|
367
381
|
}
|
|
368
382
|
|
|
369
383
|
export type EvalKernelState = NonNullable<EvalKernelResult["kernelState"]>;
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import type { ToolCallHold } from "./window.ts";
|
|
2
|
+
import { isHookedWriteTool, type WrittenFiles } from "./written-files.ts";
|
|
3
|
+
|
|
4
|
+
type SessionEvent = "tool_call_ready" | "tool_execution_end" | "turn_start";
|
|
5
|
+
type OnSessionEvent = (event: SessionEvent, handler: (event: unknown) => unknown) => void;
|
|
6
|
+
|
|
7
|
+
/** Calls that never report an end must not accumulate. */
|
|
8
|
+
const MAX_STARTED_CALLS = 256;
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Tells the written-files check about the `write` and `edit` calls the model issues itself while a detached cell is
|
|
12
|
+
* still running. The host fires `tool_call_ready` once every `tool_call` handler let the call run, with the arguments
|
|
13
|
+
* it runs with, and finishes its handlers before the call writes anything; it fires `tool_execution_end` after the
|
|
14
|
+
* call's hooks returned. The call holds the file it will write from that point to its end: a cell settling in between
|
|
15
|
+
* neither lists nor hooks it, and the end records what the call left. A call a handler blocked, or redirected, never
|
|
16
|
+
* holds the path it was first given, so it takes nothing from a cell that wrote that path. A call whose end never
|
|
17
|
+
* arrives (thrown before it finished) is let go at the next `turn_start`: a turn starts only once every call of the
|
|
18
|
+
* turn before it has ended.
|
|
19
|
+
*/
|
|
20
|
+
export function observeModelWrites(on: OnSessionEvent, current: () => WrittenFiles | undefined): void {
|
|
21
|
+
const started = new Map<string, ToolCallHold>();
|
|
22
|
+
const releaseAll = async () => {
|
|
23
|
+
const holds = [...started.values()];
|
|
24
|
+
started.clear();
|
|
25
|
+
await Promise.all(holds.map((hold) => hold.end(false)));
|
|
26
|
+
};
|
|
27
|
+
on("tool_call_ready", async (event) => {
|
|
28
|
+
const toolCallId = stringField(event, "toolCallId");
|
|
29
|
+
const toolName = stringField(event, "toolName");
|
|
30
|
+
if (toolCallId === undefined || toolName === undefined || !isHookedWriteTool(toolName)) return;
|
|
31
|
+
const previous = started.get(toolCallId);
|
|
32
|
+
started.delete(toolCallId);
|
|
33
|
+
await previous?.end(false);
|
|
34
|
+
if (started.size >= MAX_STARTED_CALLS) await releaseAll();
|
|
35
|
+
const hold = await current()?.startToolCall(toolName, field(event, "input"));
|
|
36
|
+
if (hold !== undefined) started.set(toolCallId, hold);
|
|
37
|
+
});
|
|
38
|
+
on("tool_execution_end", async (event) => {
|
|
39
|
+
const toolCallId = stringField(event, "toolCallId");
|
|
40
|
+
const hold = toolCallId === undefined ? undefined : started.get(toolCallId);
|
|
41
|
+
if (toolCallId === undefined || hold === undefined) return;
|
|
42
|
+
started.delete(toolCallId);
|
|
43
|
+
await hold.end(field(event, "isError") !== true);
|
|
44
|
+
});
|
|
45
|
+
on("turn_start", releaseAll);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function field(event: unknown, name: string): unknown {
|
|
49
|
+
return typeof event === "object" && event !== null ? Reflect.get(event, name) : undefined;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function stringField(event: unknown, name: string): string | undefined {
|
|
53
|
+
const value = field(event, name);
|
|
54
|
+
return typeof value === "string" ? value : undefined;
|
|
55
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import type { FileSignature } from "./scan-boundaries.ts";
|
|
2
|
+
|
|
3
|
+
/** The settling cell a claimed file belongs to. */
|
|
4
|
+
export interface Owner {
|
|
5
|
+
closed: boolean;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
/** A file a settlement will hook; `started` once its hooks were dispatched, so closing the cell keeps it. */
|
|
9
|
+
export interface Claim {
|
|
10
|
+
readonly owner: Owner;
|
|
11
|
+
started: boolean;
|
|
12
|
+
/** A model call took the file since the claim: the claim cedes it if not yet started, and records nothing for it. */
|
|
13
|
+
contested: boolean;
|
|
14
|
+
/** The file's baseline before this settlement advanced it to `advanced`; absent for a file new to the baseline. */
|
|
15
|
+
readonly before: FileSignature | undefined;
|
|
16
|
+
readonly advanced: FileSignature;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Who a changed file belongs to while write hooks run on it, keyed by workspace path: the settlement that claimed it,
|
|
21
|
+
* or the model `write` and `edit` calls writing it. A settlement leaves an owned file and its baseline alone.
|
|
22
|
+
*/
|
|
23
|
+
export class FileOwnership {
|
|
24
|
+
readonly #claims = new Map<string, Claim>();
|
|
25
|
+
/** How many model calls are writing and hooking each file. */
|
|
26
|
+
readonly #calls = new Map<string, number>();
|
|
27
|
+
/** Per settlement between its first look and its claims: the files model calls took meanwhile. */
|
|
28
|
+
readonly #watches = new Set<Set<string>>();
|
|
29
|
+
|
|
30
|
+
owned(path: string): boolean {
|
|
31
|
+
return this.#claims.has(path) || this.#calls.has(path);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
claim(path: string, claim: Claim): void {
|
|
35
|
+
this.#claims.set(path, claim);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
claimOf(path: string, owner: Owner): Claim | undefined {
|
|
39
|
+
const claim = this.#claims.get(path);
|
|
40
|
+
return claim?.owner === owner ? claim : undefined;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
claimsOf(owner: Owner): Array<[string, Claim]> {
|
|
44
|
+
return [...this.#claims].filter(([, claim]) => claim.owner === owner);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
endClaim(path: string): void {
|
|
48
|
+
this.#claims.delete(path);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Records every file a model call takes from now until `stop`: a settlement's look at it may be stale. */
|
|
52
|
+
watchHolds(): { readonly taken: ReadonlySet<string>; stop(): void } {
|
|
53
|
+
const taken = new Set<string>();
|
|
54
|
+
this.#watches.add(taken);
|
|
55
|
+
return { taken, stop: () => this.#watches.delete(taken) };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* A model call holds the file until it calls the returned function, once. It never waits: a settlement that looked
|
|
60
|
+
* at the file meanwhile, or claimed it, learns of the call here.
|
|
61
|
+
*/
|
|
62
|
+
holdForCall(path: string): () => void {
|
|
63
|
+
this.#calls.set(path, (this.#calls.get(path) ?? 0) + 1);
|
|
64
|
+
for (const taken of this.#watches) taken.add(path);
|
|
65
|
+
const claim = this.#claims.get(path);
|
|
66
|
+
if (claim !== undefined) claim.contested = true;
|
|
67
|
+
return () => {
|
|
68
|
+
const left = (this.#calls.get(path) ?? 1) - 1;
|
|
69
|
+
if (left > 0) this.#calls.set(path, left);
|
|
70
|
+
else this.#calls.delete(path);
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import type { AgentToolResult } from "@code-yeongyu/senpi";
|
|
2
|
+
import type { EvalToolDetails, EvalWrittenFilesDetails } from "../tool/types.ts";
|
|
3
|
+
import type { ScanSkipReason } from "./workspace-scan.ts";
|
|
4
|
+
import type { WrittenFilesReport } from "./write-hooks.ts";
|
|
5
|
+
|
|
6
|
+
export type CellWrittenFilesOutcome =
|
|
7
|
+
| { readonly kind: "written"; readonly report: WrittenFilesReport; readonly hooksAvailable: boolean }
|
|
8
|
+
| { readonly kind: "unchecked"; readonly reason: ScanSkipReason; readonly disabled: boolean }
|
|
9
|
+
| { readonly kind: "failed"; readonly message: string };
|
|
10
|
+
|
|
11
|
+
export function withWrittenFiles(
|
|
12
|
+
result: AgentToolResult<EvalToolDetails>,
|
|
13
|
+
outcome: CellWrittenFilesOutcome | undefined,
|
|
14
|
+
): AgentToolResult<EvalToolDetails> {
|
|
15
|
+
if (outcome === undefined) return result;
|
|
16
|
+
const firstImage = result.content.findIndex((part) => part.type === "image");
|
|
17
|
+
const at = firstImage === -1 ? result.content.length : firstImage;
|
|
18
|
+
return {
|
|
19
|
+
...result,
|
|
20
|
+
content: [
|
|
21
|
+
...result.content.slice(0, at),
|
|
22
|
+
{ type: "text", text: writtenFilesText(outcome) },
|
|
23
|
+
...result.content.slice(at),
|
|
24
|
+
],
|
|
25
|
+
details: { ...result.details, writtenFiles: writtenFilesDetails(outcome) },
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function writtenFilesText(outcome: CellWrittenFilesOutcome): string {
|
|
30
|
+
if (outcome.kind === "failed") return `Files written during this cell were not checked: ${outcome.message}`;
|
|
31
|
+
if (outcome.kind === "unchecked") {
|
|
32
|
+
const off = outcome.disabled ? " The check is off for the rest of this session." : "";
|
|
33
|
+
return `Files written during this cell were not checked: ${skipReasonText(outcome.reason)}.${off}`;
|
|
34
|
+
}
|
|
35
|
+
const { report } = outcome;
|
|
36
|
+
const unlisted = report.total - report.files.length;
|
|
37
|
+
return [
|
|
38
|
+
`Workspace files written during this cell (${report.total}), ${hookedPhrase(outcome)}:`,
|
|
39
|
+
...report.files.map((path) => `- ${path}`),
|
|
40
|
+
...(unlisted === 0 ? [] : [`- (${unlisted} more, not listed and not sent through the write hooks)`]),
|
|
41
|
+
...report.hookOutputs.map((output) => `[write hooks] ${output.path}\n${output.text}`),
|
|
42
|
+
...report.hookFailures.map((failure) => `[write hook failed] ${failure.path}: ${failure.error}`),
|
|
43
|
+
].join("\n");
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function skipReasonText(reason: ScanSkipReason): string {
|
|
47
|
+
if (reason === "git_unavailable") return "git is not available";
|
|
48
|
+
return reason === "over_budget" ? "the workspace scan went over its budget" : "the workspace scan failed";
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function hookedPhrase(outcome: Extract<CellWrittenFilesOutcome, { kind: "written" }>): string {
|
|
52
|
+
if (!outcome.hooksAvailable) return "which this host cannot send through the write hooks";
|
|
53
|
+
const { hooked, files } = outcome.report;
|
|
54
|
+
if (hooked === files.length) return "sent through the write hooks";
|
|
55
|
+
return `${hooked} of them sent through the write hooks`;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function writtenFilesDetails(outcome: CellWrittenFilesOutcome): EvalWrittenFilesDetails {
|
|
59
|
+
if (outcome.kind !== "written")
|
|
60
|
+
return { files: [], total: 0, hooked: 0, unchecked: outcome.kind === "failed" ? "check_failed" : outcome.reason };
|
|
61
|
+
const { files, total, hooked, hookFailures } = outcome.report;
|
|
62
|
+
return { files, total, hooked, ...(hookFailures.length === 0 ? {} : { hookFailures }) };
|
|
63
|
+
}
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { constants, type Stats } from "node:fs";
|
|
3
|
+
import { lstat, open, realpath, stat } from "node:fs/promises";
|
|
4
|
+
|
|
5
|
+
/** What a scan compares between two moments; a rewrite changes at least one of these. */
|
|
6
|
+
export interface FileSignature {
|
|
7
|
+
readonly size: number;
|
|
8
|
+
readonly mtimeMs: number;
|
|
9
|
+
readonly ctimeMs: number;
|
|
10
|
+
/** With `ino`, which file this is: differs after a rename-over write even where timestamps are too coarse to. */
|
|
11
|
+
readonly ino: number;
|
|
12
|
+
readonly dev: number;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Whether two signatures show the same state of one file: no rewrite between them. */
|
|
16
|
+
export function sameSignature(left: FileSignature, right: FileSignature): boolean {
|
|
17
|
+
return (
|
|
18
|
+
left.size === right.size &&
|
|
19
|
+
left.mtimeMs === right.mtimeMs &&
|
|
20
|
+
left.ctimeMs === right.ctimeMs &&
|
|
21
|
+
left.ino === right.ino
|
|
22
|
+
);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* What a path names, every symlink followed. `absent` is confirmed absence (nothing there, or a parent is not a
|
|
27
|
+
* directory); `unknown` is any lookup that could not tell, a permission error or a link loop among them.
|
|
28
|
+
*/
|
|
29
|
+
export type PathIdentity =
|
|
30
|
+
| { readonly kind: "found"; readonly dev: number; readonly ino: number }
|
|
31
|
+
| { readonly kind: "absent" }
|
|
32
|
+
| { readonly kind: "unknown" };
|
|
33
|
+
|
|
34
|
+
/** The filesystem as the operating system resolves it: symlinks in a path's directories are followed. */
|
|
35
|
+
export interface FsAccess {
|
|
36
|
+
/** The path with every symlink in it resolved; undefined when it does not resolve. */
|
|
37
|
+
realpath(path: string): Promise<string | undefined>;
|
|
38
|
+
/** The signature of a regular file, its last entry not followed; undefined for a symlink, anything else and a missing path. */
|
|
39
|
+
lstat(path: string): Promise<FileSignature | undefined>;
|
|
40
|
+
/** The device and inode of whatever the path names, every symlink followed. */
|
|
41
|
+
identity(path: string): Promise<PathIdentity>;
|
|
42
|
+
/**
|
|
43
|
+
* Opens the path, refusing a symlink as its last entry where the platform can, and reads at most `limit` leading
|
|
44
|
+
* bytes only when the file it opened is a regular file `accept` takes, asked after the open and before any read;
|
|
45
|
+
* undefined otherwise.
|
|
46
|
+
*/
|
|
47
|
+
read(
|
|
48
|
+
path: string,
|
|
49
|
+
limit: number,
|
|
50
|
+
accept: (opened: FileSignature) => Promise<boolean>,
|
|
51
|
+
): Promise<Uint8Array | undefined>;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export type GitOutcome =
|
|
55
|
+
| { readonly kind: "ok"; readonly stdout: string }
|
|
56
|
+
| { readonly kind: "exit"; readonly code: number }
|
|
57
|
+
/** Killed at the deadline, or its output outgrew the cap. */
|
|
58
|
+
| { readonly kind: "over_budget" }
|
|
59
|
+
| { readonly kind: "unavailable" };
|
|
60
|
+
|
|
61
|
+
export type RunGit = (
|
|
62
|
+
args: readonly string[],
|
|
63
|
+
options: { readonly cwd: string; readonly timeoutMs: number },
|
|
64
|
+
) => Promise<GitOutcome>;
|
|
65
|
+
|
|
66
|
+
const GIT_OUTPUT_LIMIT_BYTES = 4 * 1024 * 1024;
|
|
67
|
+
|
|
68
|
+
export function createNodeFsAccess(): FsAccess {
|
|
69
|
+
return { realpath: realLocation, lstat: statRegularFile, identity: identityOf, read: readLeadingBytes };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
async function identityOf(path: string): Promise<PathIdentity> {
|
|
73
|
+
try {
|
|
74
|
+
const stats = await stat(path);
|
|
75
|
+
return { kind: "found", dev: stats.dev, ino: stats.ino };
|
|
76
|
+
} catch (error) {
|
|
77
|
+
const code = error instanceof Error && "code" in error ? error.code : undefined;
|
|
78
|
+
return code === "ENOENT" || code === "ENOTDIR" ? { kind: "absent" } : { kind: "unknown" };
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
async function realLocation(path: string): Promise<string | undefined> {
|
|
83
|
+
try {
|
|
84
|
+
return await realpath(path);
|
|
85
|
+
} catch {
|
|
86
|
+
return undefined;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async function statRegularFile(path: string): Promise<FileSignature | undefined> {
|
|
91
|
+
try {
|
|
92
|
+
const stats = await lstat(path);
|
|
93
|
+
if (!stats.isFile()) return undefined;
|
|
94
|
+
return signatureOf(stats);
|
|
95
|
+
} catch {
|
|
96
|
+
return undefined;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function signatureOf(stats: Stats): FileSignature {
|
|
101
|
+
return { size: stats.size, mtimeMs: stats.mtimeMs, ctimeMs: stats.ctimeMs, ino: stats.ino, dev: stats.dev };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
async function readLeadingBytes(
|
|
105
|
+
path: string,
|
|
106
|
+
limit: number,
|
|
107
|
+
accept: (opened: FileSignature) => Promise<boolean>,
|
|
108
|
+
): Promise<Uint8Array | undefined> {
|
|
109
|
+
let handle: Awaited<ReturnType<typeof open>> | undefined;
|
|
110
|
+
try {
|
|
111
|
+
// No-follow refuses a symlink as the last entry (Windows has no such flag, `accept` decides there); non-blocking
|
|
112
|
+
// keeps a FIFO swapped in from holding the open, and the file type is checked before a byte is read.
|
|
113
|
+
handle = await open(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
|
|
114
|
+
const opened = await handle.stat();
|
|
115
|
+
if (!opened.isFile() || !(await accept(signatureOf(opened)))) return undefined;
|
|
116
|
+
const buffer = new Uint8Array(Math.min(limit, opened.size));
|
|
117
|
+
let filled = 0;
|
|
118
|
+
while (filled < buffer.length) {
|
|
119
|
+
const { bytesRead } = await handle.read(buffer, filled, buffer.length - filled, filled);
|
|
120
|
+
if (bytesRead === 0) break;
|
|
121
|
+
filled += bytesRead;
|
|
122
|
+
}
|
|
123
|
+
return buffer.subarray(0, filled);
|
|
124
|
+
} catch {
|
|
125
|
+
return undefined;
|
|
126
|
+
} finally {
|
|
127
|
+
await handle?.close();
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Runs git without taking its optional locks, so a scan never rewrites the index of a repository in use. */
|
|
132
|
+
export function createGitRunner(inheritedEnv: () => Readonly<Record<string, string | undefined>>): RunGit {
|
|
133
|
+
return (args, options) =>
|
|
134
|
+
new Promise((resolve) => {
|
|
135
|
+
// A caller's repository selection must not redirect the scan to another repository or index.
|
|
136
|
+
const {
|
|
137
|
+
GIT_DIR: _gitDir,
|
|
138
|
+
GIT_WORK_TREE: _workTree,
|
|
139
|
+
GIT_INDEX_FILE: _indexFile,
|
|
140
|
+
GIT_PREFIX: _prefix,
|
|
141
|
+
...inherited
|
|
142
|
+
} = inheritedEnv();
|
|
143
|
+
execFile(
|
|
144
|
+
"git",
|
|
145
|
+
[...args],
|
|
146
|
+
{
|
|
147
|
+
cwd: options.cwd,
|
|
148
|
+
timeout: options.timeoutMs,
|
|
149
|
+
maxBuffer: GIT_OUTPUT_LIMIT_BYTES,
|
|
150
|
+
encoding: "utf8",
|
|
151
|
+
windowsHide: true,
|
|
152
|
+
env: { ...inherited, GIT_OPTIONAL_LOCKS: "0", GIT_TERMINAL_PROMPT: "0" },
|
|
153
|
+
},
|
|
154
|
+
(error, stdout) => {
|
|
155
|
+
if (error === null) resolve({ kind: "ok", stdout });
|
|
156
|
+
else if (error.code === "ENOENT") resolve({ kind: "unavailable" });
|
|
157
|
+
else if (typeof error.code === "number") resolve({ kind: "exit", code: error.code });
|
|
158
|
+
else if (error.killed === true || error.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER")
|
|
159
|
+
resolve({ kind: "over_budget" });
|
|
160
|
+
else resolve({ kind: "exit", code: -1 });
|
|
161
|
+
},
|
|
162
|
+
);
|
|
163
|
+
});
|
|
164
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The one definition of a workspace source file (senpi#7232): a regular file inside the session workspace, outside
|
|
3
|
+
* the excluded directories and the session's own artifacts directory, that the workspace does not ignore, at most
|
|
4
|
+
* {@link SOURCE_FILE_MAX_BYTES} long, whose leading bytes are UTF-8 text. The workspace scan enforces the location, ignore and size parts; {@link isSourceText}
|
|
5
|
+
* decides the text part from the first {@link SOURCE_FILE_SNIFF_BYTES} bytes.
|
|
6
|
+
*/
|
|
7
|
+
export const SOURCE_FILE_MAX_BYTES = 1024 * 1024;
|
|
8
|
+
export const SOURCE_FILE_SNIFF_BYTES = 8 * 1024;
|
|
9
|
+
|
|
10
|
+
/** Never source, whatever the workspace's ignore rules say. */
|
|
11
|
+
export function excludedDirectories(): readonly string[] {
|
|
12
|
+
return [".git", "node_modules"];
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Whether a workspace-relative POSIX path can name a source file; a trailing slash is git's nested-repository entry. */
|
|
16
|
+
export function isSourcePath(relativePath: string): boolean {
|
|
17
|
+
if (relativePath === "" || relativePath.endsWith("/")) return false;
|
|
18
|
+
const excluded = excludedDirectories();
|
|
19
|
+
return relativePath.split("/").every((segment) => segment !== ".." && !excluded.includes(segment));
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function isSourceText(head: Uint8Array): boolean {
|
|
23
|
+
if (head.includes(0)) return false;
|
|
24
|
+
try {
|
|
25
|
+
// Streaming mode keeps a multi-byte character cut by the sniff window from counting as invalid.
|
|
26
|
+
new TextDecoder("utf-8", { fatal: true }).decode(head, { stream: true });
|
|
27
|
+
return true;
|
|
28
|
+
} catch {
|
|
29
|
+
return false;
|
|
30
|
+
}
|
|
31
|
+
}
|