@mrclrchtr/supi-context 11.1.0 → 11.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/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ # Changelog
2
+
3
+ ## [11.3.0]
4
+
5
+ - Added package-specific release notes for live context-pressure and token-use reports.
package/README.md CHANGED
@@ -55,7 +55,26 @@ interface ContextPressureSnapshot {
55
55
  }
56
56
  ```
57
57
 
58
- Use `context_report({ mode: "full" })` only when diagnostic attribution is needed. Full mode returns compact JSON for the Context Usage Report. If it exceeds Pi's normal tool-output limits, it returns a small valid-JSON envelope with the path to a temporary file containing the complete report.
58
+ Use `context_report({ mode: "full" })` only when diagnostic attribution is needed. Full mode returns `{ ...snapshot, attribution }`. Attribution contains only:
59
+
60
+ - `scaled` and `categories`
61
+ - `systemPromptBreakdown`: composition totals, instruction/context files, skills, tool snippets, and guideline sources
62
+ - `injectedFiles`: existing file, turn, token, and line records
63
+ - `toolDefinitions`: count, token estimate, and `{ name, tokens }` records
64
+
65
+ These are existing attribution estimates, not an exact or exhaustive accounting. Category scaling and detailed inventory estimates retain their separate meanings; overlapping inventories are not reconciled or summed. Raw tool descriptions, guideline text, duplicated top-level attribution fields, and provider telemetry are excluded.
66
+
67
+ If the complete compact result exceeds Pi's default output limits, the tool instead returns `{ ...snapshot, attributionFile: { path, bytes } }`, with no inline attribution. The temporary file contains the exact complete focused result, and `bytes` is its UTF-8 byte length. The path is ephemeral; no retention is guaranteed.
68
+
69
+ The registered output schema covers all three shapes. Codemode receives native data through `structuredContent`; direct calls receive compact JSON for that same object. Scripts need not parse tool content or use rendering `details`:
70
+
71
+ ```js
72
+ const snapshot = await tools.context_report({});
73
+ text({ headroomTokens: snapshot.headroomTokens, pressurePercent: snapshot.pressurePercent });
74
+ const report = await tools.context_report({ mode: "full" });
75
+ if ("attribution" in report) text(report.attribution.toolDefinitions);
76
+ else if ("attributionFile" in report) text(report.attributionFile);
77
+ ```
59
78
 
60
79
  The tool TUI never shows raw agent JSON: concise results render as a dense snapshot that expands into its metrics; full results expand into the diagnostic report.
61
80
 
@@ -77,7 +96,7 @@ To enable the agent-callable `context_report` tool, set `agentToolEnabled` to `t
77
96
 
78
97
  ```json
79
98
  {
80
- "supi-context": {
99
+ "context": {
81
100
  "agentToolEnabled": true
82
101
  }
83
102
  }
@@ -102,6 +121,6 @@ The tool is disabled by default and requires a `/reload` or restart after toggli
102
121
  - `src/entry-renderer.ts` — TUI-only custom-entry renderer for the human command
103
122
  - `src/format*.ts` and `src/report-component.ts` — Context Usage Report rendering
104
123
  - `src/snapshot-component.ts` — compact, width-safe snapshot rendering
105
- - `src/tool/guidance.ts`, `src/tool/output.ts`, and `src/tool/render.ts` — agent-tool guidance, safe full JSON output, and tool rendering
124
+ - `src/tool/context_report/{spec,result-schema,guidance,result,render}.ts` — agent-tool schema, guidance, native/direct result assembly, and human rendering
106
125
 
107
126
  Tests live under `__tests__/unit/`.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mrclrchtr/supi-core",
3
- "version": "11.1.0",
3
+ "version": "11.3.0",
4
4
  "description": "Shared settings, configuration, reporting, and session infrastructure",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -0,0 +1,110 @@
1
+ // Session-provided Web tools for SuPi child sessions (Agent Runs and Reviewer Sessions).
2
+ //
3
+ // The loaded supi-web extension answers a synchronous request on the parent event bus.
4
+ // Consumers never depend on supi-web; when it is absent or provides no tools, the
5
+ // request returns undefined and the child simply lacks Web tools.
6
+
7
+ import type { ExtensionAPI, ExtensionFactory } from "@earendil-works/pi-coding-agent";
8
+
9
+ /** Web tools that child sessions may receive when the containing session provides them. */
10
+ export const CHILD_WEB_TOOL_NAMES = [
11
+ "web_fetch_md",
12
+ "web_search",
13
+ "web_docs_search",
14
+ "web_docs_fetch",
15
+ ] as const;
16
+
17
+ /** One session-provided Web tool name. */
18
+ export type ChildWebToolName = (typeof CHILD_WEB_TOOL_NAMES)[number];
19
+
20
+ /**
21
+ * Web tools currently callable in the containing session plus a child-only extension
22
+ * factory that registers them. The factory must not capture the parent session; it may
23
+ * capture plain data such as the containing session's configuration directory.
24
+ */
25
+ export interface ChildWebToolProvision {
26
+ readonly toolNames: readonly ChildWebToolName[];
27
+ /** Register the requested subset of `toolNames` in a child session. */
28
+ readonly createFactory: (toolNames: readonly ChildWebToolName[]) => ExtensionFactory;
29
+ }
30
+
31
+ /** Plain containing-session data supplied with a child Web tool request. */
32
+ export interface ChildWebToolsRequestContext {
33
+ /**
34
+ * Working directory whose SuPi configuration governs Web settings such as Firecrawl.
35
+ * Children with a different cwd (for example a frozen Review Workspace) keep this policy.
36
+ */
37
+ readonly configCwd: string;
38
+ }
39
+
40
+ type EventBusLike = Pick<ExtensionAPI["events"], "on" | "emit">;
41
+
42
+ const REQUEST_CHANNEL = "supi:child-web-tools:request";
43
+ const RESPONSE_CHANNEL = "supi:child-web-tools:response";
44
+
45
+ interface ChildWebToolsRequest extends ChildWebToolsRequestContext {
46
+ readonly requestId: string;
47
+ }
48
+
49
+ interface ChildWebToolsResponse {
50
+ readonly requestId: string;
51
+ readonly provision: ChildWebToolProvision;
52
+ }
53
+
54
+ let nextRequestId = 0;
55
+
56
+ /**
57
+ * Answer child Web tool requests on the parent event bus. The callback must be synchronous
58
+ * because Pi's event bus does not await listeners. Returns an unsubscribe function.
59
+ */
60
+ export function provideChildWebTools(
61
+ events: EventBusLike,
62
+ resolve: (context: ChildWebToolsRequestContext) => ChildWebToolProvision | undefined,
63
+ ): () => void {
64
+ return events.on(REQUEST_CHANNEL, (data) => {
65
+ const request = data as Partial<ChildWebToolsRequest> | undefined;
66
+ if (typeof request?.requestId !== "string" || typeof request.configCwd !== "string") return;
67
+ const { requestId, configCwd } = request;
68
+ const provision = resolve({ configCwd });
69
+ if (!provision || provision.toolNames.length === 0) return;
70
+ events.emit(RESPONSE_CHANNEL, { requestId, provision } satisfies ChildWebToolsResponse);
71
+ });
72
+ }
73
+
74
+ /** Capture the Web tools the containing session currently provides, if any. */
75
+ export function requestChildWebTools(
76
+ events: EventBusLike,
77
+ context: ChildWebToolsRequestContext,
78
+ ): ChildWebToolProvision | undefined {
79
+ const requestId = `child-web-${process.pid}-${++nextRequestId}`;
80
+ let provision: ChildWebToolProvision | undefined;
81
+ const unsubscribe = events.on(RESPONSE_CHANNEL, (data) => {
82
+ const response = data as Partial<ChildWebToolsResponse> | undefined;
83
+ if (response?.requestId === requestId && response.provision) provision = response.provision;
84
+ });
85
+ try {
86
+ events.emit(REQUEST_CHANNEL, { requestId, ...context } satisfies ChildWebToolsRequest);
87
+ } finally {
88
+ unsubscribe();
89
+ }
90
+ return provision;
91
+ }
92
+
93
+ /**
94
+ * Return the Web tools callable in a session under Pi's exposure rules: active `direct`
95
+ * tools, plus registered `codemode` and `deferred` tools. `model-only` and `hidden`
96
+ * tools are not callable.
97
+ */
98
+ export function callableChildWebToolNames(
99
+ pi: Pick<ExtensionAPI, "getAllTools" | "getActiveTools">,
100
+ ): ChildWebToolName[] {
101
+ const active = new Set(pi.getActiveTools());
102
+ const exposures = new Map(
103
+ pi.getAllTools().map((tool) => [tool.name, tool.exposure ?? "direct"] as const),
104
+ );
105
+ return CHILD_WEB_TOOL_NAMES.filter((name) => {
106
+ const exposure = exposures.get(name);
107
+ if (exposure === "direct") return active.has(name);
108
+ return exposure === "codemode" || exposure === "deferred";
109
+ });
110
+ }
@@ -1,5 +1,16 @@
1
1
  // supi-core session domain — session utilities and registries.
2
2
 
3
+ export type {
4
+ ChildWebToolName,
5
+ ChildWebToolProvision,
6
+ ChildWebToolsRequestContext,
7
+ } from "./child-web-tools.ts";
8
+ export {
9
+ CHILD_WEB_TOOL_NAMES,
10
+ callableChildWebToolNames,
11
+ provideChildWebTools,
12
+ requestChildWebTools,
13
+ } from "./child-web-tools.ts";
3
14
  export { createRegistry, createSessionStateRegistry } from "./registry-utils.ts";
4
15
  export type {
5
16
  SessionCapabilitySkill,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mrclrchtr/supi-context",
3
- "version": "11.1.0",
3
+ "version": "11.3.0",
4
4
  "description": "Live context pressure and token-use reports",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -27,11 +27,12 @@
27
27
  ],
28
28
  "type": "module",
29
29
  "files": [
30
+ "CHANGELOG.md",
30
31
  "src/**/*.ts",
31
32
  "README.md"
32
33
  ],
33
34
  "dependencies": {
34
- "@mrclrchtr/supi-core": "11.1.0"
35
+ "@mrclrchtr/supi-core": "11.3.0"
35
36
  },
36
37
  "bundledDependencies": [
37
38
  "@mrclrchtr/supi-core"
@@ -0,0 +1,114 @@
1
+ import { type Static, Type } from "typebox";
2
+
3
+ const nullableNumber = Type.Union([Type.Number(), Type.Null()]);
4
+
5
+ /** Exact capacity-only result, shared by concise, inline, and file-reference paths. */
6
+ export const contextPressureSnapshotSchema = Type.Object(
7
+ {
8
+ modelName: Type.String(),
9
+ contextWindow: nullableNumber,
10
+ usedTokens: Type.Number(),
11
+ usagePercent: nullableNumber,
12
+ compactionEnabled: Type.Boolean(),
13
+ reserveTokens: Type.Number(),
14
+ headroomTokens: nullableNumber,
15
+ pressurePercent: nullableNumber,
16
+ compacted: Type.Boolean(),
17
+ approximationNote: Type.Union([Type.String(), Type.Null()]),
18
+ },
19
+ { additionalProperties: false },
20
+ );
21
+
22
+ const namedTokensSchema = Type.Object(
23
+ { name: Type.String(), tokens: Type.Number() },
24
+ { additionalProperties: false },
25
+ );
26
+
27
+ const contextFileSchema = Type.Object(
28
+ {
29
+ path: Type.String(),
30
+ tokens: Type.Number(),
31
+ lines: Type.Number(),
32
+ origin: Type.Union([Type.Literal("global"), Type.Literal("project")]),
33
+ },
34
+ { additionalProperties: false },
35
+ );
36
+
37
+ const attributionSchema = Type.Object(
38
+ {
39
+ scaled: Type.Boolean(),
40
+ categories: Type.Object(
41
+ {
42
+ systemPrompt: Type.Number(),
43
+ userMessages: Type.Number(),
44
+ assistantMessages: Type.Number(),
45
+ toolCalls: Type.Number(),
46
+ toolResults: Type.Number(),
47
+ other: Type.Number(),
48
+ },
49
+ { additionalProperties: false },
50
+ ),
51
+ systemPromptBreakdown: Type.Object(
52
+ {
53
+ base: Type.Number(),
54
+ instructionFiles: Type.Array(contextFileSchema),
55
+ contextFiles: Type.Array(contextFileSchema),
56
+ skills: Type.Array(namedTokensSchema),
57
+ guidelines: Type.Number(),
58
+ toolSnippets: Type.Number(),
59
+ toolSnippetDetails: Type.Array(namedTokensSchema),
60
+ guidelineSources: Type.Array(
61
+ Type.Object(
62
+ { source: Type.String(), tokens: Type.Number(), bulletCount: Type.Number() },
63
+ { additionalProperties: false },
64
+ ),
65
+ ),
66
+ appendText: Type.Number(),
67
+ },
68
+ { additionalProperties: false },
69
+ ),
70
+ injectedFiles: Type.Array(
71
+ Type.Object(
72
+ { file: Type.String(), turn: Type.Number(), tokens: Type.Number(), lines: Type.Number() },
73
+ { additionalProperties: false },
74
+ ),
75
+ ),
76
+ toolDefinitions: Type.Object(
77
+ { count: Type.Number(), tokens: Type.Number(), tools: Type.Array(namedTokensSchema) },
78
+ { additionalProperties: false },
79
+ ),
80
+ },
81
+ { additionalProperties: false },
82
+ );
83
+
84
+ const inlineResultSchema = Type.Object(
85
+ { ...contextPressureSnapshotSchema.properties, attribution: attributionSchema },
86
+ { additionalProperties: false },
87
+ );
88
+
89
+ const fileResultSchema = Type.Object(
90
+ {
91
+ ...contextPressureSnapshotSchema.properties,
92
+ attributionFile: Type.Object(
93
+ { path: Type.String(), bytes: Type.Integer({ minimum: 0 }) },
94
+ { additionalProperties: false },
95
+ ),
96
+ },
97
+ { additionalProperties: false },
98
+ );
99
+
100
+ /** Capacity-only, complete inline attribution, or a reference to that complete result. */
101
+ export const contextReportOutputSchema = Type.Union([
102
+ contextPressureSnapshotSchema,
103
+ inlineResultSchema,
104
+ fileResultSchema,
105
+ ]);
106
+
107
+ /** Capacity-only native result. */
108
+ export type ContextReportSnapshot = Static<typeof contextPressureSnapshotSchema>;
109
+
110
+ /** Complete focused result before applying the inline output limit. */
111
+ export type ContextReportInlineResult = Static<typeof inlineResultSchema>;
112
+
113
+ /** JSON-serializable public contract, independent of the human report details. */
114
+ export type ContextReportOutput = Static<typeof contextReportOutputSchema>;
@@ -8,7 +8,12 @@ import {
8
8
  truncateHead,
9
9
  } from "@earendil-works/pi-coding-agent";
10
10
  import type { ContextAnalysis } from "../../analysis.ts";
11
- import type { ContextPressureSnapshot } from "../../capacity.ts";
11
+ import { type ContextPressureSnapshot, createContextPressureSnapshot } from "../../capacity.ts";
12
+ import type {
13
+ ContextReportInlineResult,
14
+ ContextReportOutput,
15
+ ContextReportSnapshot,
16
+ } from "./result-schema.ts";
12
17
 
13
18
  export interface ContextToolConciseDetails {
14
19
  mode: "concise";
@@ -20,67 +25,57 @@ export interface ContextToolFullDetails {
20
25
  analysis: ContextAnalysis;
21
26
  }
22
27
 
23
- /** Mode-specific details returned to the agent and mirrored for TUI rendering. */
28
+ /** Mode-specific details retained separately for TUI rendering and reconstruction. */
24
29
  export type ContextToolDetails = ContextToolConciseDetails | ContextToolFullDetails;
25
30
 
26
- interface TruncatedOutputEnvelope {
27
- truncated: true;
28
- fullOutputPath: string;
29
- totalLines: number;
30
- totalBytes: number;
31
- maxLines: number;
32
- maxBytes: number;
33
- }
34
-
35
- /**
36
- * Serialize a diagnostic report without ever returning invalid partial JSON.
37
- *
38
- * When Pi's normal tool-output limits would truncate the report, the complete
39
- * compact JSON is stored in a temporary file and the agent receives a small,
40
- * valid JSON envelope pointing to it instead.
41
- */
42
- export async function serializeFullContextAnalysis(analysis: ContextAnalysis): Promise<string> {
43
- const fullJson = JSON.stringify(analysis);
44
- const truncation = truncateHead(fullJson, {
45
- maxLines: DEFAULT_MAX_LINES,
46
- maxBytes: DEFAULT_MAX_BYTES,
47
- });
48
-
49
- if (!truncation.truncated) {
50
- return fullJson;
51
- }
52
-
53
- const outputDir = await mkdtemp(join(tmpdir(), "supi-context-"));
54
- const fullOutputPath = join(outputDir, "context-usage-report.json");
55
- await writeFile(fullOutputPath, fullJson, "utf8");
56
-
57
- const envelope: TruncatedOutputEnvelope = {
58
- truncated: true,
59
- fullOutputPath,
60
- totalLines: truncation.totalLines,
61
- totalBytes: truncation.totalBytes,
62
- maxLines: DEFAULT_MAX_LINES,
63
- maxBytes: DEFAULT_MAX_BYTES,
64
- };
65
- return JSON.stringify(envelope);
66
- }
67
-
68
- /** Assemble the concise-mode model-facing result. */
31
+ /** Assemble the concise-mode model-facing and native result without diagnostic analysis. */
69
32
  export function buildConciseResult(
70
33
  snapshot: ContextPressureSnapshot,
71
- ): AgentToolResult<ContextToolConciseDetails> {
34
+ ): AgentToolResult<ContextToolConciseDetails> & { structuredContent: ContextReportSnapshot } {
35
+ const data = { ...snapshot };
72
36
  return {
73
- content: [{ type: "text", text: JSON.stringify(snapshot) }],
37
+ content: [{ type: "text", text: JSON.stringify(data) }],
38
+ structuredContent: data,
74
39
  details: { mode: "concise", snapshot },
75
40
  };
76
41
  }
77
42
 
78
- /** Assemble the full-mode model-facing result. */
43
+ /**
44
+ * Project existing attribution facts without reconciling overlapping estimates.
45
+ * The complete compact public result alone determines whether attribution spills;
46
+ * the human report, including excluded text, remains available only in details.
47
+ */
79
48
  export async function buildFullResult(
80
49
  analysis: ContextAnalysis,
81
- ): Promise<AgentToolResult<ContextToolFullDetails>> {
50
+ ): Promise<AgentToolResult<ContextToolFullDetails> & { structuredContent: ContextReportOutput }> {
51
+ const snapshot = createContextPressureSnapshot(analysis.modelName, analysis);
52
+ const full: ContextReportInlineResult = {
53
+ ...snapshot,
54
+ attribution: {
55
+ scaled: analysis.scaled,
56
+ categories: analysis.categories,
57
+ systemPromptBreakdown: analysis.systemPromptBreakdown,
58
+ injectedFiles: analysis.injectedFiles,
59
+ toolDefinitions: {
60
+ count: analysis.toolDefinitions.count,
61
+ tokens: analysis.toolDefinitions.tokens,
62
+ tools: analysis.toolDefinitions.tools.map(({ name, tokens }) => ({ name, tokens })),
63
+ },
64
+ },
65
+ };
66
+ let data: ContextReportOutput = full;
67
+ let text = JSON.stringify(full);
68
+ const size = truncateHead(text, { maxLines: DEFAULT_MAX_LINES, maxBytes: DEFAULT_MAX_BYTES });
69
+ if (size.truncated) {
70
+ const outputDir = await mkdtemp(join(tmpdir(), "supi-context-"));
71
+ const path = join(outputDir, "context-usage-report.json");
72
+ await writeFile(path, text, "utf8");
73
+ data = { ...snapshot, attributionFile: { path, bytes: Buffer.byteLength(text, "utf8") } };
74
+ text = JSON.stringify(data);
75
+ }
82
76
  return {
83
- content: [{ type: "text", text: await serializeFullContextAnalysis(analysis) }],
77
+ content: [{ type: "text", text }],
78
+ structuredContent: data,
84
79
  details: { mode: "full", analysis },
85
80
  };
86
81
  }
@@ -1,5 +1,5 @@
1
- import { StringEnum } from "@earendil-works/pi-ai";
2
1
  import { Type } from "typebox";
2
+ import { contextReportOutputSchema } from "./result-schema.ts";
3
3
 
4
4
  export const CONTEXT_REPORT_TOOL_NAME = "context_report";
5
5
  export const CONTEXT_REPORT_TOOL_LABEL = "Context Usage";
@@ -8,10 +8,12 @@ export const CONTEXT_REPORT_TOOL_LABEL = "Context Usage";
8
8
  export const contextReportSpec = {
9
9
  name: CONTEXT_REPORT_TOOL_NAME,
10
10
  label: CONTEXT_REPORT_TOOL_LABEL,
11
+ outputSchema: contextReportOutputSchema,
11
12
  parameters: Type.Object({
12
13
  mode: Type.Optional(
13
- StringEnum(["concise", "full"] as const, {
14
- description: "Omit for concise capacity data, or use full for the diagnostic report.",
14
+ Type.Enum(["concise", "full"] as const, {
15
+ type: "string",
16
+ description: "Omit for concise capacity data, or use full for focused attribution.",
15
17
  }),
16
18
  ),
17
19
  }),