flowtask-permission-gate 0.0.0-stage → 2.0.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/LICENSE +21 -0
- package/README.md +90 -2
- package/dist/authorizer.d.ts +16 -0
- package/dist/authorizer.js +473 -0
- package/dist/context-budget.d.ts +138 -0
- package/dist/context-budget.js +369 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +642 -0
- package/dist/layers.d.ts +104 -0
- package/dist/layers.js +185 -0
- package/dist/registration.d.ts +44 -0
- package/dist/registration.js +135 -0
- package/dist/worktree-manager-location.d.ts +17 -0
- package/dist/worktree-manager-location.js +30 -0
- package/package.json +41 -4
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
/** Per-call threshold — read (chars of `output.output`). */
|
|
2
|
+
export declare const DEFAULT_READ_THRESHOLD = 16000;
|
|
3
|
+
/** Per-call threshold — grep (chars of `output.output`). */
|
|
4
|
+
export declare const DEFAULT_GREP_THRESHOLD = 8000;
|
|
5
|
+
/** Per-call threshold — glob (chars of `output.output`). */
|
|
6
|
+
export declare const DEFAULT_GLOB_THRESHOLD = 8000;
|
|
7
|
+
/** Maximum chars delivered per runner turn (reset by the prompt hook). */
|
|
8
|
+
export declare const DEFAULT_TURN_ACCUMULATED = 32000;
|
|
9
|
+
/** `stat.size` (bytes) that without `limit`/`offset` triggers the read pre-gate. */
|
|
10
|
+
export declare const PREVENTIVE_READ_STAT_LIMIT: number;
|
|
11
|
+
/** Glob patterns that without a bounded path trigger the pre-gate (closed list). */
|
|
12
|
+
export declare const PREVENTIVE_GLOB_PATTERNS: string[];
|
|
13
|
+
/** Path segments considered unbounded by the preventive glob/grep gates. */
|
|
14
|
+
export declare const DEFAULT_BLOCKED_PATHS: string[];
|
|
15
|
+
/** grep without `include` on the root triggers the pre-gate. */
|
|
16
|
+
export declare const PREVENTIVE_GREP_NO_INCLUDE_ROOT = true;
|
|
17
|
+
/** Image/PDF attachment blocked for the runner (delegation to the Inspector). */
|
|
18
|
+
export declare const IMAGE_PDF_BLOCKED = true;
|
|
19
|
+
export type BudgetTool = "read" | "glob" | "grep";
|
|
20
|
+
/** Scope of the applied budget: per call or accumulated per turn. */
|
|
21
|
+
export type BudgetScope = "call" | "turn";
|
|
22
|
+
/** Observable degradation level of a delivery. */
|
|
23
|
+
export type DegradationLevel = "notice" | "reduced" | "turn_omitted" | "attachment_delegated" | "measurement_unavailable";
|
|
24
|
+
/** Who can handle what was omitted for context. */
|
|
25
|
+
export declare const DELEGATION_TARGET = "Inspector";
|
|
26
|
+
/** What is omitted in each tool, named in the reduced-delivery message. */
|
|
27
|
+
export declare const CONTENT_LABEL: Record<BudgetTool, string>;
|
|
28
|
+
/** How to narrow a broad request, named in the prior notice. */
|
|
29
|
+
export declare const NARROWING: Record<BudgetTool, string>;
|
|
30
|
+
export type ContextBudgetConfig = {
|
|
31
|
+
/** Per-call read threshold (chars). */
|
|
32
|
+
readThreshold: number;
|
|
33
|
+
/** Per-call grep threshold (chars). */
|
|
34
|
+
grepThreshold: number;
|
|
35
|
+
/** Per-call glob threshold (chars). */
|
|
36
|
+
globThreshold: number;
|
|
37
|
+
/** Maximum chars delivered per turn. */
|
|
38
|
+
turnAccumulated: number;
|
|
39
|
+
/** `stat.size` (bytes) that without limit/offset triggers the read pre-gate. */
|
|
40
|
+
preventiveReadStatLimit: number;
|
|
41
|
+
/** Broad glob patterns from the pre-gate closed list. */
|
|
42
|
+
preventiveGlobPatterns: string[];
|
|
43
|
+
/** Path segments considered unbounded (e.g. node_modules). */
|
|
44
|
+
blockedPaths: string[];
|
|
45
|
+
};
|
|
46
|
+
/**
|
|
47
|
+
* Loads the config with defaults; if a readable override file exists in workdir
|
|
48
|
+
* (first) or sessionDir (fallback), applies it. Fail-open: never throws.
|
|
49
|
+
*/
|
|
50
|
+
export declare function loadContextBudgetConfig(workdir: string, sessionDir?: string): ContextBudgetConfig;
|
|
51
|
+
/**
|
|
52
|
+
* Prior narrowing notice: the first broad request of the turn is announced with
|
|
53
|
+
* the way to narrow it and is not executed. It exposes no figures or content.
|
|
54
|
+
*/
|
|
55
|
+
export declare function buildNarrowingNotice(tool: BudgetTool, args: Record<string, unknown>): string;
|
|
56
|
+
/**
|
|
57
|
+
* Reduced delivery: names what was omitted, how much it weighed, and who to
|
|
58
|
+
* delegate to, without a preview of the omitted content. The budget is named by
|
|
59
|
+
* its scope, never by its figure.
|
|
60
|
+
*/
|
|
61
|
+
export declare function buildReducedDelivery(tool: BudgetTool, actual: number, scope?: BudgetScope): string;
|
|
62
|
+
/**
|
|
63
|
+
* Delivery of an image/PDF attachment: the measured text does not reflect the
|
|
64
|
+
* real cost of the attachment, so the attachment is delegated and not delivered.
|
|
65
|
+
*/
|
|
66
|
+
export declare function buildAttachmentDelivery(tool: BudgetTool, actual: number): string;
|
|
67
|
+
/**
|
|
68
|
+
* Exact fallback without preview. `tool` is a literal read/glob/grep, `actual`
|
|
69
|
+
* the real measured size, and `threshold` the applicable threshold; the figure
|
|
70
|
+
* is not published: the message names the scope of the per-call budget.
|
|
71
|
+
*/
|
|
72
|
+
export declare function buildFallback(tool: BudgetTool, actual: number, _threshold: number): string;
|
|
73
|
+
/** Observable degradation mark on the delivery metadata. */
|
|
74
|
+
export declare function buildDegradationMetadata(level: DegradationLevel, options?: {
|
|
75
|
+
budget?: BudgetScope;
|
|
76
|
+
omittedChars?: number;
|
|
77
|
+
}): Record<string, unknown>;
|
|
78
|
+
/**
|
|
79
|
+
* File targeted by a `read` call in the V2 shape (`path`) with the legacy
|
|
80
|
+
* `file` field as fallback. Returns an empty string when neither is usable.
|
|
81
|
+
*/
|
|
82
|
+
export declare function readRequestedPath(args: Record<string, unknown>): string;
|
|
83
|
+
/**
|
|
84
|
+
* Identity of the broad request. The tool prefix prevents collisions between
|
|
85
|
+
* each tool's field sets.
|
|
86
|
+
*/
|
|
87
|
+
export declare function noticeKey(tool: BudgetTool, args: Record<string, unknown>): string;
|
|
88
|
+
/** Narrowing notices already issued, per session and per broad request. */
|
|
89
|
+
export declare const PRE_GATE_NOTICES: Map<string, Set<string>>;
|
|
90
|
+
/**
|
|
91
|
+
* Registers the notice for a broad request. Returns `true` the first time (the
|
|
92
|
+
* notice is emitted and the request is not executed) and `false` if it was
|
|
93
|
+
* already emitted in this turn (the request is allowed and the delivery is
|
|
94
|
+
* reduced afterward).
|
|
95
|
+
*/
|
|
96
|
+
export declare function registerNarrowingNotice(sessionID: string, tool: BudgetTool, args: Record<string, unknown>): boolean;
|
|
97
|
+
/** Resets the narrowing notices of one session or all of them. */
|
|
98
|
+
export declare function resetNarrowingNotices(sessionID?: string): void;
|
|
99
|
+
/**
|
|
100
|
+
* Cheap read pre-gate: file without `limit`/`offset` whose `stat.size` exceeds
|
|
101
|
+
* the preventive limit. `statSize` may come from the caller's prior `statSync`;
|
|
102
|
+
* if it is `undefined` (stat failed), it does NOT block: the post-gate decides.
|
|
103
|
+
* The limit comes from the loaded config; the exported default is the fallback.
|
|
104
|
+
*/
|
|
105
|
+
export declare function shouldPreventiveBlockRead(args: Record<string, unknown>, statSize?: number, statLimit?: number): boolean;
|
|
106
|
+
/**
|
|
107
|
+
* Glob pre-gate: broad pattern from the configured closed list with an
|
|
108
|
+
* unbounded path or a blocked segment.
|
|
109
|
+
*/
|
|
110
|
+
export declare function shouldPreventiveBlockGlob(args: Record<string, unknown>, patterns?: string[], blockedPaths?: string[]): boolean;
|
|
111
|
+
/** grep pre-gate: no `include` on an unbounded path or in a blocked segment. */
|
|
112
|
+
export declare function shouldPreventiveBlockGrep(args: Record<string, unknown>, blockedPaths?: string[]): boolean;
|
|
113
|
+
type ToolOutput = {
|
|
114
|
+
output?: unknown;
|
|
115
|
+
content?: unknown;
|
|
116
|
+
metadata?: Record<string, unknown>;
|
|
117
|
+
};
|
|
118
|
+
/**
|
|
119
|
+
* Text delivered by a V2 tool result: `output` first, then `content` when it is
|
|
120
|
+
* a string. Returns undefined when the delivery cannot be measured.
|
|
121
|
+
*/
|
|
122
|
+
export declare function readDeliveredText(result: ToolOutput | undefined): string | undefined;
|
|
123
|
+
/**
|
|
124
|
+
* Applies a reduced delivery to a mutable V2 tool result: replaces the string
|
|
125
|
+
* delivery fields and merges the observable degradation metadata. Never throws.
|
|
126
|
+
*/
|
|
127
|
+
export declare function applyReducedDelivery(result: ToolOutput | undefined, reduced: string, level: DegradationLevel, options?: {
|
|
128
|
+
budget?: BudgetScope;
|
|
129
|
+
omittedChars?: number;
|
|
130
|
+
}): ToolOutput | undefined;
|
|
131
|
+
/**
|
|
132
|
+
* Detects image/PDF attachment delivery: the tool returns a short text
|
|
133
|
+
* (`Image read successfully`) plus a base64 attachment that is not reflected in
|
|
134
|
+
* `string.length` but does saturate multimodal context/memory. V2 may also
|
|
135
|
+
* deliver the payload as file parts in `content` or mark it in `metadata`.
|
|
136
|
+
*/
|
|
137
|
+
export declare function isImageOrPdfOutput(output: ToolOutput | undefined): boolean;
|
|
138
|
+
export {};
|
|
@@ -0,0 +1,369 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Context budget for the runner's read tools.
|
|
3
|
+
*
|
|
4
|
+
* Transparent tool gate on the V2 tool result (mutable `output`/`content` and
|
|
5
|
+
* `metadata`). Measures the delivered text length (proxy chars/4 tokens) and
|
|
6
|
+
* degrades the delivery by levels before omitting it:
|
|
7
|
+
*
|
|
8
|
+
* 1. `notice` — the first broad request of the turn is announced with the way
|
|
9
|
+
* to narrow it and is not executed.
|
|
10
|
+
* 2. `reduced` — a delivery that exceeds the per-call budget is reduced:
|
|
11
|
+
* it declares what was omitted, how much it weighed, and who to delegate to,
|
|
12
|
+
* without a preview.
|
|
13
|
+
* 3. `turn_omitted` — the turn total reaches the accumulated budget: the next
|
|
14
|
+
* delivery is omitted even if each piece fits on its own.
|
|
15
|
+
*
|
|
16
|
+
* Image/PDF attachments are delegated (`attachment_delegated`) and output that
|
|
17
|
+
* cannot be measured is delivered intact with a trace (`measurement_unavailable`).
|
|
18
|
+
*
|
|
19
|
+
* The limits live EXCLUSIVELY in this tool; the runner does not know the
|
|
20
|
+
* thresholds and they are not exposed in the prompt: messages name the scope of
|
|
21
|
+
* the applied budget and the real omitted size, never the figure. Optional
|
|
22
|
+
* per-file override in `.flowtask/config/context-budget.json` (fail-open to
|
|
23
|
+
* defaults).
|
|
24
|
+
*/
|
|
25
|
+
import { readFileSync } from "node:fs";
|
|
26
|
+
import { resolve } from "node:path";
|
|
27
|
+
/** Per-call threshold — read (chars of `output.output`). */
|
|
28
|
+
export const DEFAULT_READ_THRESHOLD = 16000;
|
|
29
|
+
/** Per-call threshold — grep (chars of `output.output`). */
|
|
30
|
+
export const DEFAULT_GREP_THRESHOLD = 8000;
|
|
31
|
+
/** Per-call threshold — glob (chars of `output.output`). */
|
|
32
|
+
export const DEFAULT_GLOB_THRESHOLD = 8000;
|
|
33
|
+
/** Maximum chars delivered per runner turn (reset by the prompt hook). */
|
|
34
|
+
export const DEFAULT_TURN_ACCUMULATED = 32000;
|
|
35
|
+
/** `stat.size` (bytes) that without `limit`/`offset` triggers the read pre-gate. */
|
|
36
|
+
export const PREVENTIVE_READ_STAT_LIMIT = 50 * 1024;
|
|
37
|
+
/** Glob patterns that without a bounded path trigger the pre-gate (closed list). */
|
|
38
|
+
export const PREVENTIVE_GLOB_PATTERNS = ["**/*", "**"];
|
|
39
|
+
/** Path segments considered unbounded by the preventive glob/grep gates. */
|
|
40
|
+
export const DEFAULT_BLOCKED_PATHS = ["node_modules"];
|
|
41
|
+
/** grep without `include` on the root triggers the pre-gate. */
|
|
42
|
+
export const PREVENTIVE_GREP_NO_INCLUDE_ROOT = true;
|
|
43
|
+
/** Image/PDF attachment blocked for the runner (delegation to the Inspector). */
|
|
44
|
+
export const IMAGE_PDF_BLOCKED = true;
|
|
45
|
+
/** Who can handle what was omitted for context. */
|
|
46
|
+
export const DELEGATION_TARGET = "Inspector";
|
|
47
|
+
/** What is omitted in each tool, named in the reduced-delivery message. */
|
|
48
|
+
export const CONTENT_LABEL = {
|
|
49
|
+
read: "file content",
|
|
50
|
+
grep: "matches",
|
|
51
|
+
glob: "paths",
|
|
52
|
+
};
|
|
53
|
+
/** How to narrow a broad request, named in the prior notice. */
|
|
54
|
+
export const NARROWING = {
|
|
55
|
+
read: "use `limit`/`offset` or delegate the full file to the Inspector",
|
|
56
|
+
grep: "narrow with `include` and `path`, or delegate the search to the Inspector",
|
|
57
|
+
glob: "narrow `path` or use a more specific pattern, or delegate the listing to the Inspector",
|
|
58
|
+
};
|
|
59
|
+
const CONFIG_CANDIDATES = [
|
|
60
|
+
".opencode/flowtask/config/context-budget.json",
|
|
61
|
+
".flowtask/config/context-budget.json",
|
|
62
|
+
];
|
|
63
|
+
function defaultConfig() {
|
|
64
|
+
return {
|
|
65
|
+
readThreshold: DEFAULT_READ_THRESHOLD,
|
|
66
|
+
grepThreshold: DEFAULT_GREP_THRESHOLD,
|
|
67
|
+
globThreshold: DEFAULT_GLOB_THRESHOLD,
|
|
68
|
+
turnAccumulated: DEFAULT_TURN_ACCUMULATED,
|
|
69
|
+
preventiveReadStatLimit: PREVENTIVE_READ_STAT_LIMIT,
|
|
70
|
+
preventiveGlobPatterns: [...PREVENTIVE_GLOB_PATTERNS],
|
|
71
|
+
blockedPaths: [...DEFAULT_BLOCKED_PATHS],
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
function isPositiveNumber(value) {
|
|
75
|
+
return typeof value === "number" && Number.isFinite(value) && value > 0;
|
|
76
|
+
}
|
|
77
|
+
function isStringArray(value) {
|
|
78
|
+
return Array.isArray(value) && value.every((entry) => typeof entry === "string");
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Parses the override file. Observable fail-open: invalid JSON or
|
|
82
|
+
* non-numeric/≤0 fields → `console.warn` + defaults. Never throws.
|
|
83
|
+
*/
|
|
84
|
+
function parseContextBudgetConfig(raw, filePath) {
|
|
85
|
+
let value;
|
|
86
|
+
try {
|
|
87
|
+
value = JSON.parse(raw);
|
|
88
|
+
}
|
|
89
|
+
catch {
|
|
90
|
+
console.warn(`[FlowTask Context Budget] invalid JSON in ${filePath}; using defaults.`);
|
|
91
|
+
return defaultConfig();
|
|
92
|
+
}
|
|
93
|
+
if (!value || typeof value !== "object") {
|
|
94
|
+
console.warn(`[FlowTask Context Budget] invalid configuration in ${filePath}; using defaults.`);
|
|
95
|
+
return defaultConfig();
|
|
96
|
+
}
|
|
97
|
+
const record = value;
|
|
98
|
+
const config = defaultConfig();
|
|
99
|
+
const numeric = [
|
|
100
|
+
"readThreshold",
|
|
101
|
+
"grepThreshold",
|
|
102
|
+
"globThreshold",
|
|
103
|
+
"turnAccumulated",
|
|
104
|
+
"preventiveReadStatLimit",
|
|
105
|
+
];
|
|
106
|
+
const array = ["preventiveGlobPatterns", "blockedPaths"];
|
|
107
|
+
let invalid = false;
|
|
108
|
+
for (const key of numeric) {
|
|
109
|
+
if (record[key] === undefined)
|
|
110
|
+
continue;
|
|
111
|
+
if (isPositiveNumber(record[key])) {
|
|
112
|
+
config[key] = record[key];
|
|
113
|
+
}
|
|
114
|
+
else {
|
|
115
|
+
invalid = true;
|
|
116
|
+
console.warn(`[FlowTask Context Budget] field "${key}" is not a positive number in ${filePath}; using defaults.`);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
for (const key of array) {
|
|
120
|
+
if (record[key] === undefined)
|
|
121
|
+
continue;
|
|
122
|
+
if (isStringArray(record[key])) {
|
|
123
|
+
config[key] = [...record[key]];
|
|
124
|
+
}
|
|
125
|
+
else {
|
|
126
|
+
invalid = true;
|
|
127
|
+
console.warn(`[FlowTask Context Budget] field "${key}" is not a string array in ${filePath}; using defaults.`);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
if (invalid) {
|
|
131
|
+
console.warn(`[FlowTask Context Budget] invalid configuration in ${filePath}; using defaults.`);
|
|
132
|
+
return defaultConfig();
|
|
133
|
+
}
|
|
134
|
+
return config;
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Loads the config with defaults; if a readable override file exists in workdir
|
|
138
|
+
* (first) or sessionDir (fallback), applies it. Fail-open: never throws.
|
|
139
|
+
*/
|
|
140
|
+
export function loadContextBudgetConfig(workdir, sessionDir) {
|
|
141
|
+
const directories = [workdir, sessionDir].filter((directory, index, values) => Boolean(directory) && values.indexOf(directory) === index);
|
|
142
|
+
for (const directory of directories) {
|
|
143
|
+
for (const candidate of CONFIG_CANDIDATES) {
|
|
144
|
+
const filePath = resolve(directory, candidate);
|
|
145
|
+
let raw;
|
|
146
|
+
try {
|
|
147
|
+
raw = readFileSync(filePath, "utf8");
|
|
148
|
+
}
|
|
149
|
+
catch (error) {
|
|
150
|
+
if (error.code === "ENOENT")
|
|
151
|
+
continue;
|
|
152
|
+
console.warn(`[FlowTask Context Budget] could not read ${filePath}; using defaults.`);
|
|
153
|
+
continue;
|
|
154
|
+
}
|
|
155
|
+
return parseContextBudgetConfig(raw, filePath);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
return defaultConfig();
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Prior narrowing notice: the first broad request of the turn is announced with
|
|
162
|
+
* the way to narrow it and is not executed. It exposes no figures or content.
|
|
163
|
+
*/
|
|
164
|
+
export function buildNarrowingNotice(tool, args) {
|
|
165
|
+
return `Broad \`${tool}\` request (\`${narrowingTarget(tool, args)}\`): \`${NARROWING[tool]}\`.`;
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* Reduced delivery: names what was omitted, how much it weighed, and who to
|
|
169
|
+
* delegate to, without a preview of the omitted content. The budget is named by
|
|
170
|
+
* its scope, never by its figure.
|
|
171
|
+
*/
|
|
172
|
+
export function buildReducedDelivery(tool, actual, scope = "call") {
|
|
173
|
+
const budget = scope === "turn" ? "the accumulated turn budget" : "the per-call budget";
|
|
174
|
+
return (`\`${tool}\` result reduced: \`${actual}\` chars of \`${CONTENT_LABEL[tool]}\` were omitted due to \`${budget}\`. ` +
|
|
175
|
+
`Delegate the omitted content to the Inspector or narrow path/pattern/limit/include.`);
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* Delivery of an image/PDF attachment: the measured text does not reflect the
|
|
179
|
+
* real cost of the attachment, so the attachment is delegated and not delivered.
|
|
180
|
+
*/
|
|
181
|
+
export function buildAttachmentDelivery(tool, actual) {
|
|
182
|
+
return (`\`${tool}\` attachment omitted: \`${actual}\` chars of measured text plus an image/PDF attachment. ` +
|
|
183
|
+
`Delegate the attachment to the Inspector; the runner receives no attachments.`);
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* Exact fallback without preview. `tool` is a literal read/glob/grep, `actual`
|
|
187
|
+
* the real measured size, and `threshold` the applicable threshold; the figure
|
|
188
|
+
* is not published: the message names the scope of the per-call budget.
|
|
189
|
+
*/
|
|
190
|
+
export function buildFallback(tool, actual, _threshold) {
|
|
191
|
+
return buildReducedDelivery(tool, actual, "call");
|
|
192
|
+
}
|
|
193
|
+
/** Observable degradation mark on the delivery metadata. */
|
|
194
|
+
export function buildDegradationMetadata(level, options = {}) {
|
|
195
|
+
const degradation = { level };
|
|
196
|
+
if (options.budget !== undefined)
|
|
197
|
+
degradation.budget = options.budget;
|
|
198
|
+
if (options.omittedChars !== undefined)
|
|
199
|
+
degradation.omitted_chars = options.omittedChars;
|
|
200
|
+
if (level !== "measurement_unavailable")
|
|
201
|
+
degradation.delegated_to = DELEGATION_TARGET;
|
|
202
|
+
return { degradation };
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* File targeted by a `read` call in the V2 shape (`path`) with the legacy
|
|
206
|
+
* `file` field as fallback. Returns an empty string when neither is usable.
|
|
207
|
+
*/
|
|
208
|
+
export function readRequestedPath(args) {
|
|
209
|
+
const pathValue = args?.path;
|
|
210
|
+
if (typeof pathValue === "string" && pathValue)
|
|
211
|
+
return pathValue;
|
|
212
|
+
const fileValue = args?.file;
|
|
213
|
+
return typeof fileValue === "string" ? fileValue : "";
|
|
214
|
+
}
|
|
215
|
+
/** Target of the broad request: the file or the pattern, or the absence of a window. */
|
|
216
|
+
function narrowingTarget(tool, args) {
|
|
217
|
+
const candidate = tool === "read" ? readRequestedPath(args) : args?.pattern;
|
|
218
|
+
return typeof candidate === "string" && candidate ? candidate : "no bounded window";
|
|
219
|
+
}
|
|
220
|
+
/**
|
|
221
|
+
* Identity of the broad request. The tool prefix prevents collisions between
|
|
222
|
+
* each tool's field sets.
|
|
223
|
+
*/
|
|
224
|
+
export function noticeKey(tool, args) {
|
|
225
|
+
const field = (value) => (typeof value === "string" ? value : "");
|
|
226
|
+
if (tool === "read")
|
|
227
|
+
return `read|${readRequestedPath(args)}`;
|
|
228
|
+
if (tool === "glob")
|
|
229
|
+
return `glob|${field(args?.pattern)}|${field(args?.path)}`;
|
|
230
|
+
return `grep|${field(args?.pattern)}|${field(args?.path)}|${field(args?.include)}`;
|
|
231
|
+
}
|
|
232
|
+
/** Narrowing notices already issued, per session and per broad request. */
|
|
233
|
+
export const PRE_GATE_NOTICES = new Map();
|
|
234
|
+
/**
|
|
235
|
+
* Registers the notice for a broad request. Returns `true` the first time (the
|
|
236
|
+
* notice is emitted and the request is not executed) and `false` if it was
|
|
237
|
+
* already emitted in this turn (the request is allowed and the delivery is
|
|
238
|
+
* reduced afterward).
|
|
239
|
+
*/
|
|
240
|
+
export function registerNarrowingNotice(sessionID, tool, args) {
|
|
241
|
+
const key = noticeKey(tool, args);
|
|
242
|
+
let issued = PRE_GATE_NOTICES.get(sessionID);
|
|
243
|
+
if (!issued) {
|
|
244
|
+
issued = new Set();
|
|
245
|
+
PRE_GATE_NOTICES.set(sessionID, issued);
|
|
246
|
+
}
|
|
247
|
+
if (issued.has(key))
|
|
248
|
+
return false;
|
|
249
|
+
issued.add(key);
|
|
250
|
+
return true;
|
|
251
|
+
}
|
|
252
|
+
/** Resets the narrowing notices of one session or all of them. */
|
|
253
|
+
export function resetNarrowingNotices(sessionID) {
|
|
254
|
+
if (sessionID === undefined) {
|
|
255
|
+
PRE_GATE_NOTICES.clear();
|
|
256
|
+
return;
|
|
257
|
+
}
|
|
258
|
+
PRE_GATE_NOTICES.delete(sessionID);
|
|
259
|
+
}
|
|
260
|
+
/**
|
|
261
|
+
* Cheap read pre-gate: file without `limit`/`offset` whose `stat.size` exceeds
|
|
262
|
+
* the preventive limit. `statSize` may come from the caller's prior `statSync`;
|
|
263
|
+
* if it is `undefined` (stat failed), it does NOT block: the post-gate decides.
|
|
264
|
+
* The limit comes from the loaded config; the exported default is the fallback.
|
|
265
|
+
*/
|
|
266
|
+
export function shouldPreventiveBlockRead(args, statSize, statLimit = PREVENTIVE_READ_STAT_LIMIT) {
|
|
267
|
+
const file = readRequestedPath(args);
|
|
268
|
+
if (!file)
|
|
269
|
+
return false;
|
|
270
|
+
const hasWindow = args.limit !== undefined || args.offset !== undefined;
|
|
271
|
+
if (hasWindow)
|
|
272
|
+
return false;
|
|
273
|
+
if (statSize !== undefined && statSize > statLimit)
|
|
274
|
+
return true;
|
|
275
|
+
return false;
|
|
276
|
+
}
|
|
277
|
+
/** The path is the root, the current directory, or absent. */
|
|
278
|
+
function isUnboundedPath(pathValue) {
|
|
279
|
+
return (pathValue === undefined ||
|
|
280
|
+
pathValue === null ||
|
|
281
|
+
pathValue === "" ||
|
|
282
|
+
pathValue === "." ||
|
|
283
|
+
pathValue === "./" ||
|
|
284
|
+
pathValue === "/");
|
|
285
|
+
}
|
|
286
|
+
function hitsBlockedPath(pathValue, blockedPaths) {
|
|
287
|
+
if (typeof pathValue !== "string")
|
|
288
|
+
return false;
|
|
289
|
+
const segments = pathValue.split(/[\\/]/);
|
|
290
|
+
return segments.some((segment) => blockedPaths.includes(segment));
|
|
291
|
+
}
|
|
292
|
+
/**
|
|
293
|
+
* Glob pre-gate: broad pattern from the configured closed list with an
|
|
294
|
+
* unbounded path or a blocked segment.
|
|
295
|
+
*/
|
|
296
|
+
export function shouldPreventiveBlockGlob(args, patterns = PREVENTIVE_GLOB_PATTERNS, blockedPaths = DEFAULT_BLOCKED_PATHS) {
|
|
297
|
+
const pattern = String(args?.pattern ?? "");
|
|
298
|
+
if (!patterns.includes(pattern))
|
|
299
|
+
return false;
|
|
300
|
+
const pathValue = args?.path;
|
|
301
|
+
return isUnboundedPath(pathValue) || hitsBlockedPath(pathValue, blockedPaths);
|
|
302
|
+
}
|
|
303
|
+
/** grep pre-gate: no `include` on an unbounded path or in a blocked segment. */
|
|
304
|
+
export function shouldPreventiveBlockGrep(args, blockedPaths = DEFAULT_BLOCKED_PATHS) {
|
|
305
|
+
if (!PREVENTIVE_GREP_NO_INCLUDE_ROOT)
|
|
306
|
+
return false;
|
|
307
|
+
const include = args?.include;
|
|
308
|
+
if (include !== undefined && include !== null && include !== "")
|
|
309
|
+
return false;
|
|
310
|
+
const pathValue = args?.path;
|
|
311
|
+
return isUnboundedPath(pathValue) || hitsBlockedPath(pathValue, blockedPaths);
|
|
312
|
+
}
|
|
313
|
+
/**
|
|
314
|
+
* Text delivered by a V2 tool result: `output` first, then `content` when it is
|
|
315
|
+
* a string. Returns undefined when the delivery cannot be measured.
|
|
316
|
+
*/
|
|
317
|
+
export function readDeliveredText(result) {
|
|
318
|
+
if (!result)
|
|
319
|
+
return undefined;
|
|
320
|
+
if (typeof result.output === "string")
|
|
321
|
+
return result.output;
|
|
322
|
+
if (typeof result.content === "string")
|
|
323
|
+
return result.content;
|
|
324
|
+
return undefined;
|
|
325
|
+
}
|
|
326
|
+
/**
|
|
327
|
+
* Applies a reduced delivery to a mutable V2 tool result: replaces the string
|
|
328
|
+
* delivery fields and merges the observable degradation metadata. Never throws.
|
|
329
|
+
*/
|
|
330
|
+
export function applyReducedDelivery(result, reduced, level, options = {}) {
|
|
331
|
+
if (!result)
|
|
332
|
+
return result;
|
|
333
|
+
if (typeof result.output === "string")
|
|
334
|
+
result.output = reduced;
|
|
335
|
+
if (typeof result.content === "string")
|
|
336
|
+
result.content = reduced;
|
|
337
|
+
result.metadata = {
|
|
338
|
+
...(result.metadata ?? {}),
|
|
339
|
+
truncated: true,
|
|
340
|
+
...buildDegradationMetadata(level, options),
|
|
341
|
+
};
|
|
342
|
+
return result;
|
|
343
|
+
}
|
|
344
|
+
/**
|
|
345
|
+
* Detects image/PDF attachment delivery: the tool returns a short text
|
|
346
|
+
* (`Image read successfully`) plus a base64 attachment that is not reflected in
|
|
347
|
+
* `string.length` but does saturate multimodal context/memory. V2 may also
|
|
348
|
+
* deliver the payload as file parts in `content` or mark it in `metadata`.
|
|
349
|
+
*/
|
|
350
|
+
export function isImageOrPdfOutput(output) {
|
|
351
|
+
if (!output)
|
|
352
|
+
return false;
|
|
353
|
+
if (typeof output.output === "string" && output.output === "Image read successfully")
|
|
354
|
+
return true;
|
|
355
|
+
const attachment = output.metadata?.attachment;
|
|
356
|
+
if (attachment !== undefined && attachment !== null && attachment !== false)
|
|
357
|
+
return true;
|
|
358
|
+
if (Array.isArray(output.content)) {
|
|
359
|
+
return output.content.some((part) => {
|
|
360
|
+
if (!part || typeof part !== "object")
|
|
361
|
+
return false;
|
|
362
|
+
const record = part;
|
|
363
|
+
return (record.type === "file" &&
|
|
364
|
+
typeof record.mime === "string" &&
|
|
365
|
+
(record.mime.startsWith("image/") || record.mime === "application/pdf"));
|
|
366
|
+
});
|
|
367
|
+
}
|
|
368
|
+
return false;
|
|
369
|
+
}
|
package/dist/index.d.ts
ADDED