@mrclrchtr/supi-context 11.0.1 → 11.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md 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.0.1",
3
+ "version": "11.2.0",
4
4
  "description": "Shared settings, configuration, reporting, and session infrastructure",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -14,6 +14,8 @@ export interface DebugRegistryConfig {
14
14
  enabled: boolean;
15
15
  /** What the agent-callable debug tool may return. */
16
16
  agentAccess: DebugAgentAccess;
17
+ /** Whether Agent Run retrospective capture is explicitly enabled. */
18
+ agentRunRetrospectivesEnabled: boolean;
17
19
  /** Maximum number of session-local events to keep in memory. */
18
20
  maxEvents: number;
19
21
  }
@@ -21,6 +23,7 @@ export interface DebugRegistryConfig {
21
23
  export const DEBUG_REGISTRY_DEFAULTS: DebugRegistryConfig = {
22
24
  enabled: false,
23
25
  agentAccess: "sanitized",
26
+ agentRunRetrospectivesEnabled: false,
24
27
  maxEvents: 100,
25
28
  };
26
29
 
@@ -75,6 +78,9 @@ export interface DebugEventQueryResult {
75
78
  /** Receives a sanitized event whenever the registry records one. */
76
79
  export type DebugEventListener = (event: DebugEventView) => void;
77
80
 
81
+ /** Receives sanitized events for persistence; separate from ordinary event subscriptions. */
82
+ export type DebugPersistenceSink = (event: DebugEventView) => void;
83
+
78
84
  export interface DebugSummary {
79
85
  total: number;
80
86
  byLevel: Partial<Record<DebugLevel, number>>;
@@ -85,6 +91,7 @@ interface DebugRegistryState {
85
91
  config: DebugRegistryConfig;
86
92
  events: DebugEvent[];
87
93
  listeners: Set<DebugEventListener>;
94
+ persistenceSinks: Set<DebugPersistenceSink>;
88
95
  nextId: number;
89
96
  }
90
97
 
@@ -111,13 +118,15 @@ function getState(): DebugRegistryState {
111
118
  config: cloneConfig(DEBUG_REGISTRY_DEFAULTS),
112
119
  events: [],
113
120
  listeners: new Set(),
121
+ persistenceSinks: new Set(),
114
122
  nextId: 1,
115
123
  };
116
124
  (globalThis as Record<symbol, unknown>)[REGISTRY_KEY] = state;
117
125
  }
118
126
  // Keep the shared registry compatible with extension reloads that reuse an
119
- // instance created before listeners existed.
127
+ // instance created before listener sets existed.
120
128
  if (!state.listeners) state.listeners = new Set();
129
+ if (!state.persistenceSinks) state.persistenceSinks = new Set();
121
130
  return state;
122
131
  }
123
132
 
@@ -200,6 +209,19 @@ export function isDebugRegistryEnabled(): boolean {
200
209
  return getState().config.enabled;
201
210
  }
202
211
 
212
+ /**
213
+ * Return whether a retrospective can be captured: Debug and its explicit opt-in
214
+ * must be enabled, and at least one persistence sink must be registered.
215
+ */
216
+ export function canRecordAgentRunRetrospective(): boolean {
217
+ const state = getState();
218
+ return (
219
+ state.config.enabled &&
220
+ state.config.agentRunRetrospectivesEnabled &&
221
+ state.persistenceSinks.size > 0
222
+ );
223
+ }
224
+
203
225
  /** Best-effort redaction helper for data exposed through sanitized debug views. */
204
226
  export function redactDebugData<T>(value: T): T {
205
227
  return redactValue(value, 8) as T;
@@ -226,6 +248,16 @@ export function subscribeDebugEvents(listener: DebugEventListener): () => void {
226
248
  return () => state.listeners.delete(listener);
227
249
  }
228
250
 
251
+ /**
252
+ * Register a sanitized event persistence sink. Sinks are tracked separately from
253
+ * ordinary listeners so eligibility checks only succeed when logging is active.
254
+ */
255
+ export function subscribeDebugPersistence(sink: DebugPersistenceSink): () => void {
256
+ const state = getState();
257
+ state.persistenceSinks.add(sink);
258
+ return () => state.persistenceSinks.delete(sink);
259
+ }
260
+
229
261
  /** Record a session-local debug event if debugging is enabled. */
230
262
  export function recordDebugEvent(input: DebugEventInput): DebugEvent | null {
231
263
  const state = getState();
@@ -251,6 +283,13 @@ export function recordDebugEvent(input: DebugEventInput): DebugEvent | null {
251
283
  // Debug-event consumers must not alter producer behavior.
252
284
  }
253
285
  }
286
+ for (const sink of state.persistenceSinks) {
287
+ try {
288
+ sink(toSanitizedView(event));
289
+ } catch {
290
+ // Persistence failures must not alter producer behavior.
291
+ }
292
+ }
254
293
  return {
255
294
  ...event,
256
295
  data: event.data === undefined ? undefined : redactDebugData(event.data),
@@ -309,5 +348,6 @@ export function resetDebugRegistry(): void {
309
348
  state.config = cloneConfig(DEBUG_REGISTRY_DEFAULTS);
310
349
  state.events = [];
311
350
  state.listeners.clear();
351
+ state.persistenceSinks.clear();
312
352
  state.nextId = 1;
313
353
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mrclrchtr/supi-context",
3
- "version": "11.0.1",
3
+ "version": "11.2.0",
4
4
  "description": "Live context pressure and token-use reports",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -31,7 +31,7 @@
31
31
  "README.md"
32
32
  ],
33
33
  "dependencies": {
34
- "@mrclrchtr/supi-core": "11.0.1"
34
+ "@mrclrchtr/supi-core": "11.2.0"
35
35
  },
36
36
  "bundledDependencies": [
37
37
  "@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,6 @@
1
1
  import { StringEnum } from "@earendil-works/pi-ai";
2
2
  import { Type } from "typebox";
3
+ import { contextReportOutputSchema } from "./result-schema.ts";
3
4
 
4
5
  export const CONTEXT_REPORT_TOOL_NAME = "context_report";
5
6
  export const CONTEXT_REPORT_TOOL_LABEL = "Context Usage";
@@ -8,10 +9,11 @@ export const CONTEXT_REPORT_TOOL_LABEL = "Context Usage";
8
9
  export const contextReportSpec = {
9
10
  name: CONTEXT_REPORT_TOOL_NAME,
10
11
  label: CONTEXT_REPORT_TOOL_LABEL,
12
+ outputSchema: contextReportOutputSchema,
11
13
  parameters: Type.Object({
12
14
  mode: Type.Optional(
13
15
  StringEnum(["concise", "full"] as const, {
14
- description: "Omit for concise capacity data, or use full for the diagnostic report.",
16
+ description: "Omit for concise capacity data, or use full for focused attribution.",
15
17
  }),
16
18
  ),
17
19
  }),