@mrclrchtr/supi-settings 1.8.1

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.
Files changed (32) hide show
  1. package/node_modules/@mrclrchtr/supi-core/README.md +97 -0
  2. package/node_modules/@mrclrchtr/supi-core/package.json +57 -0
  3. package/node_modules/@mrclrchtr/supi-core/src/api.ts +30 -0
  4. package/node_modules/@mrclrchtr/supi-core/src/config/config-settings.ts +76 -0
  5. package/node_modules/@mrclrchtr/supi-core/src/config/config.ts +186 -0
  6. package/node_modules/@mrclrchtr/supi-core/src/config.ts +11 -0
  7. package/node_modules/@mrclrchtr/supi-core/src/context/context-messages.ts +119 -0
  8. package/node_modules/@mrclrchtr/supi-core/src/context/context-provider-registry.ts +36 -0
  9. package/node_modules/@mrclrchtr/supi-core/src/context/context-tag.ts +31 -0
  10. package/node_modules/@mrclrchtr/supi-core/src/context.ts +16 -0
  11. package/node_modules/@mrclrchtr/supi-core/src/debug-registry.ts +255 -0
  12. package/node_modules/@mrclrchtr/supi-core/src/index.ts +30 -0
  13. package/node_modules/@mrclrchtr/supi-core/src/path-utils.ts +40 -0
  14. package/node_modules/@mrclrchtr/supi-core/src/path.ts +2 -0
  15. package/node_modules/@mrclrchtr/supi-core/src/project-roots.ts +170 -0
  16. package/node_modules/@mrclrchtr/supi-core/src/project.ts +15 -0
  17. package/node_modules/@mrclrchtr/supi-core/src/registry-utils.ts +86 -0
  18. package/node_modules/@mrclrchtr/supi-core/src/session-utils.ts +29 -0
  19. package/node_modules/@mrclrchtr/supi-core/src/session.ts +4 -0
  20. package/node_modules/@mrclrchtr/supi-core/src/settings/settings-command.ts +15 -0
  21. package/node_modules/@mrclrchtr/supi-core/src/settings/settings-registry.ts +41 -0
  22. package/node_modules/@mrclrchtr/supi-core/src/settings/settings-ui.ts +226 -0
  23. package/node_modules/@mrclrchtr/supi-core/src/settings-ui.ts +2 -0
  24. package/node_modules/@mrclrchtr/supi-core/src/settings.ts +9 -0
  25. package/node_modules/@mrclrchtr/supi-core/src/substrate-types.ts +11 -0
  26. package/node_modules/@mrclrchtr/supi-core/src/terminal.ts +60 -0
  27. package/node_modules/@mrclrchtr/supi-core/src/tool-framework.ts +116 -0
  28. package/node_modules/@mrclrchtr/supi-core/src/types.ts +2 -0
  29. package/package.json +58 -0
  30. package/src/api.ts +1 -0
  31. package/src/extension.ts +6 -0
  32. package/src/index.ts +1 -0
@@ -0,0 +1,97 @@
1
+ ![SuPi](assets/logo.png)
2
+
3
+ # @mrclrchtr/supi-core
4
+
5
+ Shared infrastructure for SuPi extensions.
6
+
7
+ This is a **pure library** — it does not register any pi commands or tools. The `/supi-settings` command is now available through `@mrclrchtr/supi-settings`.
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ pnpm add @mrclrchtr/supi-core
13
+ ```
14
+
15
+ ## Package surfaces
16
+
17
+ - `@mrclrchtr/supi-core/api` — reusable helpers for other packages and extensions
18
+
19
+ ## What you get from the API
20
+
21
+ ### Config helpers
22
+
23
+ - `loadSupiConfig()` — merged config with resolution order `defaults <- global <- project`
24
+ - `loadSupiConfigForScope()` — load one scope at a time for settings UIs
25
+ - `writeSupiConfig()` — persist values
26
+ - `removeSupiConfigKey()` — remove a key or override
27
+
28
+ Config file locations:
29
+
30
+ - global: `~/.pi/agent/supi/config.json`
31
+ - project: `.pi/supi/config.json`
32
+
33
+ ### Settings helpers
34
+
35
+ - `registerSettings()` — register an arbitrary settings section
36
+ - `registerConfigSettings()` — register a config-backed settings section with scoped persistence helpers
37
+ - `registerSettingsCommand()` — register `/supi-settings`
38
+ - `openSettingsOverlay()` — open the shared settings UI directly
39
+ - `createInputSubmenu()` — helper for simple text-entry submenus
40
+
41
+ The built-in settings UI supports:
42
+
43
+ - project/global scope toggle
44
+ - grouped extension sections
45
+ - searchable setting lists
46
+
47
+ ### Context helpers
48
+
49
+ - `wrapExtensionContext()` — wrap injected text in SuPi's `<extension-context>` tag
50
+ - `findLastUserMessageIndex()`
51
+ - `getContextToken()`
52
+ - `getPromptContent()`
53
+ - `pruneAndReorderContextMessages()`
54
+ - `restorePromptContent()`
55
+
56
+ ### Shared registries
57
+
58
+ - context-provider registry for `/supi-context`
59
+ - debug-event registry for producers that want shared debug capture
60
+ - settings registry used by `/supi-settings`
61
+
62
+ ### Project and session helpers
63
+
64
+ - project-root detection and directory walking helpers such as `findProjectRoot()` and `walkProject()`
65
+ - active-branch session helper: `getActiveBranchEntries()`
66
+ - terminal helpers such as `formatTitle()`, `signalWaiting()`, and `signalDone()`
67
+
68
+ ## Example
69
+
70
+ ```ts
71
+ import { loadSupiConfig, registerConfigSettings, wrapExtensionContext } from "@mrclrchtr/supi-core/api";
72
+
73
+ const config = loadSupiConfig("my-extension", process.cwd(), {
74
+ enabled: true,
75
+ });
76
+
77
+ registerConfigSettings({
78
+ id: "my-extension",
79
+ label: "My Extension",
80
+ section: "my-extension",
81
+ defaults: { enabled: true },
82
+ buildItems: () => [],
83
+ persistChange: () => {},
84
+ });
85
+
86
+ const message = wrapExtensionContext("my-extension", "hello", {
87
+ file: "CLAUDE.md",
88
+ turn: 1,
89
+ });
90
+ ```
91
+
92
+ ## Source
93
+
94
+ - `src/api.ts` — exported library surface
95
+ - `src/config.ts` — shared config loading and writing
96
+ - `src/config-settings.ts` — config-backed settings registration helper
97
+ - `src/settings-ui.ts` — shared settings overlay
@@ -0,0 +1,57 @@
1
+ {
2
+ "name": "@mrclrchtr/supi-core",
3
+ "version": "1.8.1",
4
+ "description": "SuPi core — shared infrastructure for SuPi extensions (XML context tags, config system)",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/mrclrchtr/supi.git"
9
+ },
10
+ "publishConfig": {
11
+ "access": "public"
12
+ },
13
+ "keywords": [
14
+ "pi",
15
+ "pi-coding-agent"
16
+ ],
17
+ "files": [
18
+ "src/**/*.ts",
19
+ "!__tests__"
20
+ ],
21
+ "peerDependencies": {
22
+ "@earendil-works/pi-coding-agent": "*",
23
+ "@earendil-works/pi-tui": "*",
24
+ "typebox": "*"
25
+ },
26
+ "peerDependenciesMeta": {
27
+ "@earendil-works/pi-coding-agent": {
28
+ "optional": true
29
+ },
30
+ "@earendil-works/pi-tui": {
31
+ "optional": true
32
+ },
33
+ "typebox": {
34
+ "optional": true
35
+ }
36
+ },
37
+ "devDependencies": {
38
+ "@types/node": "25.9.1",
39
+ "vitest": "4.1.7"
40
+ },
41
+ "main": "src/api.ts",
42
+ "exports": {
43
+ "./api": "./src/api.ts",
44
+ "./config": "./src/config.ts",
45
+ "./context": "./src/context.ts",
46
+ "./debug": "./src/debug-registry.ts",
47
+ "./package.json": "./package.json",
48
+ "./path": "./src/path.ts",
49
+ "./project": "./src/project.ts",
50
+ "./session": "./src/session.ts",
51
+ "./settings": "./src/settings.ts",
52
+ "./settings-ui": "./src/settings-ui.ts",
53
+ "./terminal": "./src/terminal.ts",
54
+ "./tool-framework": "./src/tool-framework.ts",
55
+ "./types": "./src/types.ts"
56
+ }
57
+ }
@@ -0,0 +1,30 @@
1
+ // supi-core — shared infrastructure for SuPi extensions.
2
+ // Provides XML context tag wrapping, unified config system, context-message utilities,
3
+ // settings registry for supi-wide TUI settings, and a shared tool-spec/registration framework.
4
+ //
5
+ // Convenience barrel — re-exports all domain entry points.
6
+ // For lighter imports, use one of the domain subpaths directly
7
+ // (e.g. @mrclrchtr/supi-core/config, @mrclrchtr/supi-core/context).
8
+
9
+ // biome-ignore lint/performance/noReExportAll: intentional convenience barrel
10
+ export * from "./config.ts";
11
+ // biome-ignore lint/performance/noReExportAll: intentional convenience barrel
12
+ export * from "./context.ts";
13
+ // biome-ignore lint/performance/noReExportAll: intentional convenience barrel
14
+ export * from "./debug-registry.ts";
15
+ // biome-ignore lint/performance/noReExportAll: intentional convenience barrel
16
+ export * from "./path.ts";
17
+ // biome-ignore lint/performance/noReExportAll: intentional convenience barrel
18
+ export * from "./project.ts";
19
+ // biome-ignore lint/performance/noReExportAll: intentional convenience barrel
20
+ export * from "./session.ts";
21
+ // biome-ignore lint/performance/noReExportAll: intentional convenience barrel
22
+ export * from "./settings.ts";
23
+ // biome-ignore lint/performance/noReExportAll: intentional convenience barrel
24
+ export * from "./settings-ui.ts";
25
+ // biome-ignore lint/performance/noReExportAll: intentional convenience barrel
26
+ export * from "./terminal.ts";
27
+ // biome-ignore lint/performance/noReExportAll: intentional convenience barrel
28
+ export * from "./tool-framework.ts";
29
+ // biome-ignore lint/performance/noReExportAll: intentional convenience barrel
30
+ export * from "./types.ts";
@@ -0,0 +1,76 @@
1
+ // Config-aware settings helper for SuPi config-backed settings sections.
2
+ // Wraps registerSettings() and centralizes selected-scope loading + scoped persistence.
3
+
4
+ import type { SettingItem } from "@earendil-works/pi-tui";
5
+ import type { SettingsScope } from "../settings/settings-registry.ts";
6
+ import { registerSettings } from "../settings/settings-registry.ts";
7
+ import { loadSupiConfigForScope, removeSupiConfigKey, writeSupiConfig } from "./config.ts";
8
+
9
+ export interface ConfigSettingsHelpers {
10
+ /** Write a key to the selected scope's config section. */
11
+ set(key: string, value: unknown): void;
12
+ /** Remove a key from the selected scope's config section. */
13
+ unset(key: string): void;
14
+ }
15
+
16
+ export interface ConfigSettingsOptions<T> {
17
+ /** Extension identifier — e.g. "lsp", "claude-md" */
18
+ id: string;
19
+ /** Human-readable label shown in the UI */
20
+ label: string;
21
+ /** SuPi config section name — e.g. "lsp", "claude-md" */
22
+ section: string;
23
+ /** Default config values */
24
+ defaults: T;
25
+ /** Build SettingItem[] from scoped config. Called by loadValues. */
26
+ buildItems: (settings: T, scope: SettingsScope, cwd: string) => SettingItem[];
27
+ /** Handle a settings change with scoped persistence helpers. */
28
+ persistChange: (
29
+ scope: SettingsScope,
30
+ cwd: string,
31
+ settingId: string,
32
+ value: string,
33
+ helpers: ConfigSettingsHelpers,
34
+ ) => void;
35
+ /** Optional home directory for config resolution (testing). */
36
+ homeDir?: string;
37
+ }
38
+
39
+ /**
40
+ * Register a config-backed settings section.
41
+ *
42
+ * Loads display values from the selected scope only (`defaults <- selected scope`)
43
+ * instead of merged effective runtime config. Provides scoped `set` / `unset`
44
+ * persistence helpers so extensions don't need to wire `writeSupiConfig` /
45
+ * `removeSupiConfigKey` by hand.
46
+ */
47
+ export function registerConfigSettings<T>(options: ConfigSettingsOptions<T>): void {
48
+ registerSettings({
49
+ id: options.id,
50
+ label: options.label,
51
+ loadValues: (scope, cwd) => {
52
+ const settings = loadSupiConfigForScope(options.section, cwd, options.defaults, {
53
+ scope,
54
+ homeDir: options.homeDir,
55
+ });
56
+ return options.buildItems(settings, scope, cwd);
57
+ },
58
+ persistChange: (scope, cwd, settingId, value) => {
59
+ const helpers: ConfigSettingsHelpers = {
60
+ set: (key, val) => {
61
+ writeSupiConfig(
62
+ { section: options.section, scope, cwd },
63
+ { [key]: val },
64
+ { homeDir: options.homeDir },
65
+ );
66
+ },
67
+ unset: (key) => {
68
+ removeSupiConfigKey({ section: options.section, scope, cwd }, key, {
69
+ homeDir: options.homeDir,
70
+ });
71
+ },
72
+ };
73
+ options.persistChange(scope, cwd, settingId, value, helpers);
74
+ },
75
+ });
76
+ }
@@ -0,0 +1,186 @@
1
+ // Shared config system for SuPi extensions.
2
+ //
3
+ // Global config: ~/.pi/agent/supi/config.json
4
+ // Project config: .pi/supi/config.json (relative to cwd)
5
+ // Resolution: hardcoded defaults ← global ← project
6
+
7
+ import * as fs from "node:fs";
8
+ import * as os from "node:os";
9
+ import * as path from "node:path";
10
+
11
+ const GLOBAL_CONFIG_DIR = ".pi/agent/supi";
12
+ const PROJECT_CONFIG_DIR = ".pi/supi";
13
+ const CONFIG_FILE = "config.json";
14
+
15
+ function getGlobalConfigPath(homeDir?: string): string {
16
+ return path.join(homeDir ?? os.homedir(), GLOBAL_CONFIG_DIR, CONFIG_FILE);
17
+ }
18
+
19
+ function getProjectConfigPath(cwd: string): string {
20
+ return path.join(cwd, PROJECT_CONFIG_DIR, CONFIG_FILE);
21
+ }
22
+
23
+ export function readJsonFile(filePath: string): Record<string, unknown> | null {
24
+ let content: string;
25
+ try {
26
+ content = fs.readFileSync(filePath, "utf-8");
27
+ } catch {
28
+ // ENOENT or permission error — silent, file may not exist
29
+ return null;
30
+ }
31
+
32
+ let parsed: unknown;
33
+ try {
34
+ parsed = JSON.parse(content);
35
+ } catch {
36
+ // biome-ignore lint/suspicious/noConsole: deliberate config parse warning
37
+ console.warn(`[supi-core] Failed to parse config file, ignoring: ${filePath}`);
38
+ return null;
39
+ }
40
+
41
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
42
+ return parsed as Record<string, unknown>;
43
+ }
44
+
45
+ // biome-ignore lint/suspicious/noConsole: deliberate config parse warning
46
+ console.warn(`[supi-core] Config file root is not an object, ignoring: ${filePath}`);
47
+ return null;
48
+ }
49
+
50
+ function shallowMerge<T>(base: T, ...overrides: Array<Record<string, unknown> | null>): T {
51
+ let result = { ...base };
52
+ for (const override of overrides) {
53
+ if (!override) continue;
54
+ result = { ...result, ...override };
55
+ }
56
+ return result;
57
+ }
58
+
59
+ export interface SupiConfigOptions {
60
+ homeDir?: string;
61
+ }
62
+
63
+ /**
64
+ * Load and merge config for a given extension section.
65
+ *
66
+ * Resolution order: defaults ← global ← project
67
+ */
68
+ export function loadSupiConfig<T>(
69
+ section: string,
70
+ cwd: string,
71
+ defaults: T,
72
+ options?: SupiConfigOptions,
73
+ ): T {
74
+ const globalConfig = readJsonFile(getGlobalConfigPath(options?.homeDir));
75
+ const projectConfig = readJsonFile(getProjectConfigPath(cwd));
76
+
77
+ const globalSection = extractSection(globalConfig, section);
78
+ const projectSection = extractSection(projectConfig, section);
79
+
80
+ return shallowMerge(defaults, globalSection, projectSection);
81
+ }
82
+
83
+ /**
84
+ * Load config for a single scope only.
85
+ *
86
+ * Resolution order: defaults ← selected scope
87
+ *
88
+ * This is useful for settings UIs that need to show the raw values stored in
89
+ * one scope, rather than the effective merged config.
90
+ */
91
+ export function loadSupiConfigForScope<T>(
92
+ section: string,
93
+ cwd: string,
94
+ defaults: T,
95
+ options: { scope: "global" | "project" } & SupiConfigOptions,
96
+ ): T {
97
+ const config =
98
+ options.scope === "global"
99
+ ? readJsonFile(getGlobalConfigPath(options.homeDir))
100
+ : readJsonFile(getProjectConfigPath(cwd));
101
+
102
+ const scopedSection = extractSection(config, section);
103
+ return shallowMerge(defaults, scopedSection);
104
+ }
105
+
106
+ export interface SupiConfigLocation {
107
+ section: string;
108
+ scope: "global" | "project";
109
+ cwd: string;
110
+ }
111
+
112
+ /**
113
+ * Write config values for a given extension section.
114
+ */
115
+ export function writeSupiConfig(
116
+ loc: SupiConfigLocation,
117
+ value: Record<string, unknown>,
118
+ options?: SupiConfigOptions,
119
+ ): void {
120
+ const configPath =
121
+ loc.scope === "global" ? getGlobalConfigPath(options?.homeDir) : getProjectConfigPath(loc.cwd);
122
+
123
+ const dir = path.dirname(configPath);
124
+ fs.mkdirSync(dir, { recursive: true });
125
+
126
+ const existing = readJsonFile(configPath) ?? {};
127
+ existing[loc.section] = {
128
+ ...((existing[loc.section] as Record<string, unknown>) ?? {}),
129
+ ...value,
130
+ };
131
+
132
+ fs.writeFileSync(configPath, `${JSON.stringify(existing, null, 2)}\n`, "utf-8");
133
+ }
134
+
135
+ /**
136
+ * Remove a key from a config section.
137
+ * Used by `interval default` to remove the project override.
138
+ */
139
+ export function removeSupiConfigKey(
140
+ loc: SupiConfigLocation,
141
+ key: string,
142
+ options?: SupiConfigOptions,
143
+ ): void {
144
+ const configPath =
145
+ loc.scope === "global" ? getGlobalConfigPath(options?.homeDir) : getProjectConfigPath(loc.cwd);
146
+
147
+ const existing = readJsonFile(configPath);
148
+ if (!existing) return;
149
+
150
+ const sectionData = existing[loc.section] as Record<string, unknown> | undefined;
151
+ if (!sectionData) return;
152
+
153
+ delete sectionData[key];
154
+
155
+ if (Object.keys(sectionData).length === 0) {
156
+ delete existing[loc.section];
157
+ }
158
+
159
+ const dir = path.dirname(configPath);
160
+ fs.mkdirSync(dir, { recursive: true });
161
+
162
+ const content = Object.keys(existing).length > 0 ? `${JSON.stringify(existing, null, 2)}\n` : "";
163
+
164
+ if (content) {
165
+ // Directory guaranteed to exist since we just read from it
166
+ fs.writeFileSync(configPath, content, "utf-8");
167
+ } else {
168
+ try {
169
+ fs.unlinkSync(configPath);
170
+ } catch {
171
+ // File may not exist
172
+ }
173
+ }
174
+ }
175
+
176
+ function extractSection(
177
+ config: Record<string, unknown> | null,
178
+ section: string,
179
+ ): Record<string, unknown> | null {
180
+ if (!config) return null;
181
+ const data = config[section];
182
+ if (typeof data === "object" && data !== null && !Array.isArray(data)) {
183
+ return data as Record<string, unknown>;
184
+ }
185
+ return null;
186
+ }
@@ -0,0 +1,11 @@
1
+ // supi-core config domain — config loading and config-settings helpers.
2
+ export type { SupiConfigLocation, SupiConfigOptions } from "./config/config.ts";
3
+ export {
4
+ loadSupiConfig,
5
+ loadSupiConfigForScope,
6
+ readJsonFile,
7
+ removeSupiConfigKey,
8
+ writeSupiConfig,
9
+ } from "./config/config.ts";
10
+ export type { ConfigSettingsHelpers, ConfigSettingsOptions } from "./config/config-settings.ts";
11
+ export { registerConfigSettings } from "./config/config-settings.ts";
@@ -0,0 +1,119 @@
1
+ // Shared context-message utilities for SuPi extensions.
2
+ //
3
+ // Provides a generic prune-and-reorder pattern for extensions that inject
4
+ // managed context messages (via `before_agent_start` with a `customType` and
5
+ // `contextToken`) and maintain them via the `context` event.
6
+
7
+ /**
8
+ * Minimal message shape needed for context-message operations.
9
+ * Extensions cast their event.messages entries to this type.
10
+ */
11
+ export type ContextMessageLike = {
12
+ role?: string;
13
+ customType?: string;
14
+ content?: unknown;
15
+ details?: unknown;
16
+ };
17
+
18
+ /**
19
+ * Extract the `contextToken` string from a message's `details` object.
20
+ * Returns `null` when the token is absent or not a string.
21
+ */
22
+ export function getContextToken(details: unknown): string | null {
23
+ if (!details || typeof details !== "object") return null;
24
+ const token = (details as { contextToken?: unknown }).contextToken;
25
+ return typeof token === "string" ? token : null;
26
+ }
27
+
28
+ /**
29
+ * Find the index of the last message with `role: "user"`.
30
+ * Returns `-1` when no user message exists.
31
+ */
32
+ export function findLastUserMessageIndex<T extends ContextMessageLike>(messages: T[]): number {
33
+ for (let index = messages.length - 1; index >= 0; index--) {
34
+ if (messages[index]?.role === "user") return index;
35
+ }
36
+ return -1;
37
+ }
38
+
39
+ /**
40
+ * Filter stale context messages and reorder the active one before the last user message.
41
+ *
42
+ * - Removes all messages matching `customType` whose token differs from `activeToken`.
43
+ * - When `activeToken` is `null`, removes **all** messages of that `customType`.
44
+ * - If the active context message is after the last user message, moves it before.
45
+ *
46
+ * Returns the modified array, or the original reference when no changes were needed.
47
+ */
48
+ export function pruneAndReorderContextMessages<T extends ContextMessageLike>(
49
+ messages: T[],
50
+ customType: string,
51
+ activeToken: string | null,
52
+ ): T[] {
53
+ // Remove stale messages of the target customType
54
+ const filtered = messages.filter((message) => {
55
+ if (message.customType !== customType) return true;
56
+ if (!activeToken) return false;
57
+ return getContextToken(message.details) === activeToken;
58
+ });
59
+
60
+ if (!activeToken) return filtered;
61
+
62
+ // Find the active context message
63
+ const contextIndex = filtered.findIndex(
64
+ (message) =>
65
+ message.customType === customType && getContextToken(message.details) === activeToken,
66
+ );
67
+ if (contextIndex === -1) return filtered;
68
+
69
+ // Find the last user message
70
+ const userIndex = findLastUserMessageIndex(filtered);
71
+ if (userIndex === -1 || contextIndex < userIndex) return filtered;
72
+
73
+ // Move context message before last user message
74
+ const next = [...filtered];
75
+ const [contextMessage] = next.splice(contextIndex, 1);
76
+ if (!contextMessage) return filtered;
77
+ next.splice(userIndex, 0, contextMessage);
78
+ return next;
79
+ }
80
+
81
+ /**
82
+ * Restore the raw prompt content on a context message that was swapped for display text.
83
+ *
84
+ * Extensions using `registerMessageRenderer` store their LLM-facing content in
85
+ * `details.promptContent` and put a human-readable summary in `content`. This function
86
+ * reverses the swap so the model sees the original prompt content.
87
+ *
88
+ * Returns the original array reference when no change is needed.
89
+ */
90
+ export function restorePromptContent<T extends ContextMessageLike>(
91
+ messages: T[],
92
+ customType: string,
93
+ activeToken: string | null,
94
+ ): T[] {
95
+ if (!activeToken) return messages;
96
+
97
+ const index = messages.findIndex(
98
+ (message) =>
99
+ message.customType === customType && getContextToken(message.details) === activeToken,
100
+ );
101
+ if (index === -1) return messages;
102
+
103
+ const promptContent = getPromptContent(messages[index]?.details);
104
+ if (!promptContent || messages[index]?.content === promptContent) return messages;
105
+
106
+ const next = [...messages];
107
+ next[index] = { ...next[index], content: promptContent };
108
+ return next;
109
+ }
110
+
111
+ /**
112
+ * Extract the `promptContent` string from a message's `details` object.
113
+ * Returns `null` when absent or not a string.
114
+ */
115
+ export function getPromptContent(details: unknown): string | null {
116
+ if (!details || typeof details !== "object") return null;
117
+ const promptContent = (details as { promptContent?: unknown }).promptContent;
118
+ return typeof promptContent === "string" ? promptContent : null;
119
+ }
@@ -0,0 +1,36 @@
1
+ // Context provider registry for SuPi extensions.
2
+ //
3
+ // Extensions declare context data providers via `registerContextProvider()` during their
4
+ // factory function. The `/supi-context` command reads them via `getRegisteredContextProviders()`.
5
+
6
+ import { createRegistry } from "../registry-utils.ts";
7
+
8
+ export interface ContextProvider {
9
+ /** Unique identifier — e.g. "rtk" */
10
+ id: string;
11
+ /** Human-readable label shown in the report */
12
+ label: string;
13
+ /** Return structured data for display, or null when unavailable. */
14
+ getData: () => Record<string, string | number> | null;
15
+ }
16
+
17
+ const registry = createRegistry<ContextProvider>("context-provider-registry");
18
+
19
+ /**
20
+ * Register a context data provider for an extension.
21
+ * Call during the extension factory function (not async handlers).
22
+ * Duplicate ids replace the previous registration.
23
+ */
24
+ export function registerContextProvider(provider: ContextProvider): void {
25
+ registry.register(provider.id, provider);
26
+ }
27
+
28
+ /** Get all registered context providers in registration order. */
29
+ export function getRegisteredContextProviders(): ContextProvider[] {
30
+ return registry.getAll();
31
+ }
32
+
33
+ /** Clear the registry — used by tests. */
34
+ export function clearRegisteredContextProviders(): void {
35
+ registry.clear();
36
+ }
@@ -0,0 +1,31 @@
1
+ // XML context tag wrapping for SuPi extensions.
2
+ //
3
+ // Produces machine-parseable <extension-context> blocks that:
4
+ // - Are LLM-friendly (structured XML)
5
+ // - Carry metadata via attributes (source, file, turn, etc.)
6
+ // - Can be reconstructed from session history via regex
7
+
8
+ /**
9
+ * Wrap content in an `<extension-context>` XML tag.
10
+ *
11
+ * @param source - Extension identifier (e.g. "supi-claude-md", "supi-lsp")
12
+ * @param content - The text content to wrap
13
+ * @param attrs - Optional additional attributes (rendered as key="value")
14
+ * @returns Formatted XML string
15
+ */
16
+ export function wrapExtensionContext(
17
+ source: string,
18
+ content: string,
19
+ attrs?: Record<string, string | number>,
20
+ ): string {
21
+ const attrParts = [`source="${source}"`];
22
+
23
+ if (attrs) {
24
+ for (const [key, value] of Object.entries(attrs)) {
25
+ attrParts.push(`${key}="${String(value)}"`);
26
+ }
27
+ }
28
+
29
+ const openTag = `<extension-context ${attrParts.join(" ")}>`;
30
+ return `${openTag}\n${content}\n</extension-context>`;
31
+ }
@@ -0,0 +1,16 @@
1
+ // supi-core context domain — context messages, providers, and XML tags.
2
+ export type { ContextMessageLike } from "./context/context-messages.ts";
3
+ export {
4
+ findLastUserMessageIndex,
5
+ getContextToken,
6
+ getPromptContent,
7
+ pruneAndReorderContextMessages,
8
+ restorePromptContent,
9
+ } from "./context/context-messages.ts";
10
+ export type { ContextProvider } from "./context/context-provider-registry.ts";
11
+ export {
12
+ clearRegisteredContextProviders,
13
+ getRegisteredContextProviders,
14
+ registerContextProvider,
15
+ } from "./context/context-provider-registry.ts";
16
+ export { wrapExtensionContext } from "./context/context-tag.ts";