@phi-code-admin/phi-code 0.83.0 → 0.84.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 (41) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/extensions/phi/btw/LICENSE +21 -0
  3. package/extensions/phi/btw/btw-ui.ts +238 -0
  4. package/extensions/phi/btw/btw.ts +363 -0
  5. package/extensions/phi/btw/index.ts +17 -0
  6. package/extensions/phi/btw/prompts/btw-system.txt +9 -0
  7. package/extensions/phi/chrome/LICENSE +21 -0
  8. package/extensions/phi/chrome/browser-extension/manifest.json +26 -0
  9. package/extensions/phi/chrome/browser-extension/service_worker.js +2388 -0
  10. package/extensions/phi/chrome/browser-extension/snapshot_injected.js +677 -0
  11. package/extensions/phi/chrome/index.ts +1799 -0
  12. package/extensions/phi/goal/LICENSE +21 -0
  13. package/extensions/phi/goal/index.ts +784 -0
  14. package/extensions/phi/todo/LICENSE +21 -0
  15. package/extensions/phi/todo/config.ts +14 -0
  16. package/extensions/phi/todo/index.ts +113 -0
  17. package/extensions/phi/todo/locales/de.json +17 -0
  18. package/extensions/phi/todo/locales/en.json +15 -0
  19. package/extensions/phi/todo/locales/es.json +17 -0
  20. package/extensions/phi/todo/locales/fr.json +17 -0
  21. package/extensions/phi/todo/locales/pt-BR.json +17 -0
  22. package/extensions/phi/todo/locales/pt.json +17 -0
  23. package/extensions/phi/todo/locales/ru.json +17 -0
  24. package/extensions/phi/todo/locales/uk.json +17 -0
  25. package/extensions/phi/todo/rpiv-config/config.ts +223 -0
  26. package/extensions/phi/todo/rpiv-config/index.ts +12 -0
  27. package/extensions/phi/todo/state/i18n-bridge.ts +65 -0
  28. package/extensions/phi/todo/state/invariants.ts +20 -0
  29. package/extensions/phi/todo/state/replay.ts +38 -0
  30. package/extensions/phi/todo/state/selectors.ts +107 -0
  31. package/extensions/phi/todo/state/state-reducer.ts +187 -0
  32. package/extensions/phi/todo/state/state.ts +18 -0
  33. package/extensions/phi/todo/state/store.ts +54 -0
  34. package/extensions/phi/todo/state/task-graph.ts +57 -0
  35. package/extensions/phi/todo/todo-overlay.ts +194 -0
  36. package/extensions/phi/todo/todo.ts +146 -0
  37. package/extensions/phi/todo/tool/response-envelope.ts +94 -0
  38. package/extensions/phi/todo/tool/types.ts +128 -0
  39. package/extensions/phi/todo/view/format.ts +162 -0
  40. package/package.json +1 -1
  41. package/scripts/postinstall.cjs +10 -5
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 juicesharp
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,14 @@
1
+ import type { GuidanceFields } from "./rpiv-config/index.js";
2
+ import { configPath, loadJsonConfig, validateGuidanceFields } from "./rpiv-config/index.js";
3
+
4
+ const CONFIG_PATH = configPath("rpiv-todo");
5
+
6
+ interface TodoConfig {
7
+ guidance?: GuidanceFields;
8
+ }
9
+
10
+ export function loadConfig(): TodoConfig {
11
+ return loadJsonConfig<TodoConfig>(CONFIG_PATH);
12
+ }
13
+
14
+ export { validateGuidanceFields };
@@ -0,0 +1,113 @@
1
+ /**
2
+ * rpiv-todo — Pi extension. Registers the `todo` tool, `/todos` slash
3
+ * command, and the persistent TodoOverlay widget.
4
+ *
5
+ * TUI chrome strings localize at render time via the i18n bridge. Strings are
6
+ * registered with rpiv-i18n here, once, at module init — but only when the
7
+ * SDK is actually installed. If `@juicesharp/rpiv-i18n` is missing (standalone
8
+ * install of just this package), the dynamic-load shim no-ops and the bridge's
9
+ * `t(key, fallback)` returns the inline English literal at every call site.
10
+ * The extension stays online either way.
11
+ *
12
+ * Adding a locale: drop `locales/<code>.json` next to en.json (mirroring the
13
+ * key set). No edit needed here — `registerLocalesFromDir` iterates
14
+ * `SUPPORTED_LOCALES` from the SDK. See `@juicesharp/rpiv-i18n` README →
15
+ * "Contributing translations" for the full convention.
16
+ *
17
+ * Extracted from rpiv-pi@7525a5d. Tool name "todo" and widget key
18
+ * "rpiv-todos" preserved verbatim so existing session history replays
19
+ * correctly after upgrade.
20
+ */
21
+
22
+ import type { ExtensionAPI } from "phi-code";
23
+ import { I18N_NAMESPACE } from "./state/i18n-bridge.js";
24
+ import { replayFromBranch } from "./state/replay.js";
25
+ import { replaceState } from "./state/store.js";
26
+ import { registerTodosCommand, registerTodoTool, TOOL_NAME } from "./todo.js";
27
+ import { TodoOverlay } from "./todo-overlay.js";
28
+
29
+ type I18nLoader = {
30
+ registerLocalesFromDir: (namespace: string, packageUrl: string, options?: { label?: string }) => void;
31
+ };
32
+
33
+ // Dynamic import keeps `@juicesharp/rpiv-i18n` a soft optional peer: when the
34
+ // SDK is installed alongside this package the strings register and
35
+ // `/languages` flips them live; when it isn't, the import rejects here, we
36
+ // no-op, and the bridge's English-fallback shim keeps the extension online.
37
+ //
38
+ // The `/loader` subpath is used instead of the SDK entry so the i18n-ui +
39
+ // pi-tui modules are not pulled into our load graph just to register strings.
40
+ try {
41
+ const i18nLoaderSpecifier: string = "@juicesharp/rpiv-i18n/loader";
42
+ const sdk = (await import(i18nLoaderSpecifier)) as I18nLoader;
43
+ sdk.registerLocalesFromDir(I18N_NAMESPACE, import.meta.url, { label: "rpiv-todo" });
44
+ } catch {
45
+ // SDK absent — extension still loads with English-only UI.
46
+ }
47
+
48
+ // pi-core's ExtensionRunner throws this exact phrase from an invalidated ctx
49
+ // proxy after session replacement/reload. Match the stable substring so genuine
50
+ // replay bugs still propagate instead of being silently swallowed.
51
+ function isStaleCtxError(e: unknown): boolean {
52
+ return /stale after session replacement/.test(String(e));
53
+ }
54
+
55
+ export default function (pi: ExtensionAPI) {
56
+ // Todo overlay widget — constructed lazily at the first session_start with UI.
57
+ let todoOverlay: TodoOverlay | undefined;
58
+
59
+ registerTodoTool(pi);
60
+ registerTodosCommand(pi);
61
+
62
+ pi.on("session_start", async (_event, ctx) => {
63
+ replaceState(replayFromBranch(ctx));
64
+ if (ctx.hasUI) {
65
+ todoOverlay ??= new TodoOverlay();
66
+ todoOverlay.setUICtx(ctx.ui);
67
+ todoOverlay.resetCompletedDisplayState();
68
+ todoOverlay.update();
69
+ }
70
+ });
71
+
72
+ pi.on("session_compact", async (_event, ctx) => {
73
+ // Auto-compaction races session disposal: pi-core invalidates the
74
+ // extension runner while still emitting session_compact, so `ctx` may be
75
+ // a dead proxy whose getters throw the stale error. The compacting session
76
+ // is being discarded — the replacement session's session_start replays
77
+ // state — so keep current state on a stale ctx. Other errors are real
78
+ // replay bugs and must propagate.
79
+ try {
80
+ replaceState(replayFromBranch(ctx));
81
+ } catch (e) {
82
+ if (!isStaleCtxError(e)) throw e;
83
+ }
84
+ todoOverlay?.resetCompletedDisplayState();
85
+ todoOverlay?.update();
86
+ });
87
+
88
+ pi.on("session_tree", async (_event, ctx) => {
89
+ try {
90
+ replaceState(replayFromBranch(ctx));
91
+ } catch (e) {
92
+ if (!isStaleCtxError(e)) throw e;
93
+ }
94
+ todoOverlay?.resetCompletedDisplayState();
95
+ todoOverlay?.update();
96
+ });
97
+
98
+ pi.on("session_shutdown", async () => {
99
+ todoOverlay?.dispose();
100
+ todoOverlay = undefined;
101
+ });
102
+
103
+ // Reads getTodos() at render time; do NOT call replayFromBranch here
104
+ // (branch is stale — message_end runs after tool_execution_end).
105
+ pi.on("tool_execution_end", async (event) => {
106
+ if (event.toolName !== TOOL_NAME || event.isError) return;
107
+ todoOverlay?.update();
108
+ });
109
+
110
+ pi.on("agent_start", async () => {
111
+ todoOverlay?.hideCompletedTasksFromPreviousTurn();
112
+ });
113
+ }
@@ -0,0 +1,17 @@
1
+ {
2
+ "_meta.notes": "Auto-translated draft. Native-speaker review welcome via PR. Unicode box-drawing characters (──) stay untranslated. Note: 'overlay.more' renders as '+5 weitere' which is grammatically loose for plural agreement — accepted for badge brevity.",
3
+
4
+ "status.pending": "ausstehend",
5
+ "status.in_progress": "in Bearbeitung",
6
+ "status.completed": "erledigt",
7
+ "status.deleted": "gelöscht",
8
+
9
+ "overlay.heading": "Todos",
10
+ "overlay.more": "weitere",
11
+
12
+ "command.no_todos": "Noch keine Todos. Bitte den Agenten, welche hinzuzufügen!",
13
+ "command.requires_interactive": "/todos erfordert den interaktiven Modus",
14
+ "command.section.pending": "── Ausstehend ──",
15
+ "command.section.in_progress": "── In Bearbeitung ──",
16
+ "command.section.completed": "── Erledigt ──"
17
+ }
@@ -0,0 +1,15 @@
1
+ {
2
+ "status.pending": "pending",
3
+ "status.in_progress": "in progress",
4
+ "status.completed": "completed",
5
+ "status.deleted": "deleted",
6
+
7
+ "overlay.heading": "Todos",
8
+ "overlay.more": "more",
9
+
10
+ "command.no_todos": "No todos yet. Ask the agent to add some!",
11
+ "command.requires_interactive": "/todos requires interactive mode",
12
+ "command.section.pending": "── Pending ──",
13
+ "command.section.in_progress": "── In Progress ──",
14
+ "command.section.completed": "── Completed ──"
15
+ }
@@ -0,0 +1,17 @@
1
+ {
2
+ "_meta.notes": "Auto-translated draft. Native-speaker review welcome via PR. Unicode box-drawing characters (──) stay untranslated.",
3
+
4
+ "status.pending": "pendientes",
5
+ "status.in_progress": "en curso",
6
+ "status.completed": "completadas",
7
+ "status.deleted": "eliminada",
8
+
9
+ "overlay.heading": "Tareas",
10
+ "overlay.more": "más",
11
+
12
+ "command.no_todos": "Sin tareas aún. ¡Pídele al agente que añada algunas!",
13
+ "command.requires_interactive": "/todos requiere modo interactivo",
14
+ "command.section.pending": "── Pendientes ──",
15
+ "command.section.in_progress": "── En curso ──",
16
+ "command.section.completed": "── Completadas ──"
17
+ }
@@ -0,0 +1,17 @@
1
+ {
2
+ "_meta.notes": "Auto-translated draft. Native-speaker review welcome via PR. Unicode box-drawing characters (──) stay untranslated.",
3
+
4
+ "status.pending": "en attente",
5
+ "status.in_progress": "en cours",
6
+ "status.completed": "terminées",
7
+ "status.deleted": "supprimée",
8
+
9
+ "overlay.heading": "Tâches",
10
+ "overlay.more": "autres",
11
+
12
+ "command.no_todos": "Pas encore de tâches. Demandez à l'agent d'en ajouter !",
13
+ "command.requires_interactive": "/todos nécessite le mode interactif",
14
+ "command.section.pending": "── En attente ──",
15
+ "command.section.in_progress": "── En cours ──",
16
+ "command.section.completed": "── Terminées ──"
17
+ }
@@ -0,0 +1,17 @@
1
+ {
2
+ "_meta.notes": "Auto-translated draft. Native-speaker review welcome via PR. Unicode box-drawing characters (──) stay untranslated.",
3
+
4
+ "status.pending": "pendentes",
5
+ "status.in_progress": "em andamento",
6
+ "status.completed": "concluídas",
7
+ "status.deleted": "excluída",
8
+
9
+ "overlay.heading": "Tarefas",
10
+ "overlay.more": "mais",
11
+
12
+ "command.no_todos": "Nenhuma tarefa ainda. Peça ao agente para adicionar algumas!",
13
+ "command.requires_interactive": "/todos requer modo interativo",
14
+ "command.section.pending": "── Pendentes ──",
15
+ "command.section.in_progress": "── Em andamento ──",
16
+ "command.section.completed": "── Concluídas ──"
17
+ }
@@ -0,0 +1,17 @@
1
+ {
2
+ "_meta.notes": "Auto-translated draft. Native-speaker review welcome via PR. Unicode box-drawing characters (──) stay untranslated.",
3
+
4
+ "status.pending": "pendentes",
5
+ "status.in_progress": "em curso",
6
+ "status.completed": "concluídas",
7
+ "status.deleted": "eliminada",
8
+
9
+ "overlay.heading": "Tarefas",
10
+ "overlay.more": "mais",
11
+
12
+ "command.no_todos": "Sem tarefas ainda. Peça ao agente para adicionar algumas!",
13
+ "command.requires_interactive": "/todos requer modo interativo",
14
+ "command.section.pending": "── Pendentes ──",
15
+ "command.section.in_progress": "── Em curso ──",
16
+ "command.section.completed": "── Concluídas ──"
17
+ }
@@ -0,0 +1,17 @@
1
+ {
2
+ "_meta.notes": "Автоперевод. Приветствуется проверка носителем языка через PR. Символы юникода (──) не переводятся.",
3
+
4
+ "status.pending": "ожидание",
5
+ "status.in_progress": "в работе",
6
+ "status.completed": "выполнено",
7
+ "status.deleted": "удалена",
8
+
9
+ "overlay.heading": "Задачи",
10
+ "overlay.more": "ещё",
11
+
12
+ "command.no_todos": "Задач пока нет. Попросите агента добавить!",
13
+ "command.requires_interactive": "/todos требует интерактивного режима",
14
+ "command.section.pending": "── Ожидание ──",
15
+ "command.section.in_progress": "── В работе ──",
16
+ "command.section.completed": "── Выполнено ──"
17
+ }
@@ -0,0 +1,17 @@
1
+ {
2
+ "_meta.notes": "Автопереклад. Привітна перевірка носієм мови через PR. Символи юнікоду (──) не перекладаються.",
3
+
4
+ "status.pending": "очікування",
5
+ "status.in_progress": "у роботі",
6
+ "status.completed": "виконано",
7
+ "status.deleted": "видалено",
8
+
9
+ "overlay.heading": "Завдання",
10
+ "overlay.more": "ще",
11
+
12
+ "command.no_todos": "Завдань поки немає. Попросіть агента додати!",
13
+ "command.requires_interactive": "/todos потребує інтерактивного режиму",
14
+ "command.section.pending": "── Очікування ──",
15
+ "command.section.in_progress": "── У роботі ──",
16
+ "command.section.completed": "── Виконано ──"
17
+ }
@@ -0,0 +1,223 @@
1
+ /**
2
+ * rpiv-config — shared config I/O utilities for rpiv-mono sibling packages.
3
+ *
4
+ * Provides JSON config load/save with crash-resistant defaults, path resolution,
5
+ * guidance-field validation, env-var fallback, and TypeBox-driven schema validation.
6
+ * Stateless — no module-level singletons, no globalThis caches, no side effects.
7
+ */
8
+
9
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
10
+ import { homedir } from "node:os";
11
+ import { dirname, join } from "node:path";
12
+ import { type Static, type TObject, Type } from "typebox";
13
+ import { Value } from "typebox/value";
14
+
15
+ // ---------------------------------------------------------------------------
16
+ // Path resolution
17
+ // ---------------------------------------------------------------------------
18
+
19
+ /**
20
+ * Resolve a config file path under `~/.config/<name>/`.
21
+ *
22
+ * @param name — package directory name (e.g. "rpiv-todo")
23
+ * @param file — config filename (defaults to "config.json")
24
+ * @returns absolute path to the config file
25
+ */
26
+ export function configPath(name: string, file: string = "config.json"): string {
27
+ return join(homedir(), ".config", name, file);
28
+ }
29
+
30
+ // ---------------------------------------------------------------------------
31
+ // JSON config load — Variant A (with typeof guard) universally
32
+ // ---------------------------------------------------------------------------
33
+
34
+ /**
35
+ * Load and parse a JSON config file.
36
+ *
37
+ * Returns `{}` for missing files, malformed JSON, or non-plain-object values.
38
+ * The typeof guard fixes a latent bug where valid non-object JSON
39
+ * (e.g. `"hello"`, `42`, `null`) passes through the cast. Arrays are also
40
+ * rejected — `typeof [] === "object"` in JavaScript, but config files are
41
+ * always plain objects.
42
+ */
43
+ export function loadJsonConfig<T>(path: string): T {
44
+ if (!existsSync(path)) return {} as T;
45
+ try {
46
+ const parsed = JSON.parse(readFileSync(path, "utf-8")) as unknown;
47
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return {} as T;
48
+ return parsed as T;
49
+ } catch (err) {
50
+ // Diagnostic for malformed-JSON path. Silent save + silent load otherwise
51
+ // produce identical user-visible symptoms (state reverts on next start)
52
+ // with zero diagnostic surface — the user cannot tell "never saved" from
53
+ // "saved-but-unreadable." Warning is owner-only since the file lives in
54
+ // the user's HOME.
55
+ console.warn(`rpiv-config: invalid JSON at ${path}, using default ({}) — ${(err as Error).message}`);
56
+ return {} as T;
57
+ }
58
+ }
59
+
60
+ // ---------------------------------------------------------------------------
61
+ // JSON config save — best-effort void
62
+ // ---------------------------------------------------------------------------
63
+
64
+ /** File mode for config files (user read/write only). */
65
+ const CONFIG_FILE_MODE = 0o600;
66
+
67
+ /**
68
+ * Persist a config object as formatted JSON. Returns `true` on successful
69
+ * mkdir+write, `false` on filesystem failure (disk full, EACCES, EROFS, …).
70
+ *
71
+ * Every current rpiv-* save call site is user-initiated and shows a
72
+ * "Saved …" notification — callers MUST guard the success notification on
73
+ * the boolean return so a silent disk failure can't make the success message
74
+ * lie on disk-full / EACCES.
75
+ *
76
+ * The chmod step is best-effort and never affects the return value: some
77
+ * filesystems (tmpfs, network mounts, Windows-style perms) silently ignore
78
+ * chmod and there is no portable way to enforce 0600 perms across platforms.
79
+ * Callers that genuinely don't care about persistence outcome can discard
80
+ * the return — TypeScript does not warn on ignored `boolean`.
81
+ */
82
+ export function saveJsonConfig(path: string, data: unknown): boolean {
83
+ try {
84
+ mkdirSync(dirname(path), { recursive: true });
85
+ writeFileSync(path, `${JSON.stringify(data, null, 2)}\n`, "utf-8");
86
+ } catch {
87
+ return false;
88
+ }
89
+ try {
90
+ chmodSync(path, CONFIG_FILE_MODE);
91
+ } catch {
92
+ // chmod may fail on some filesystems — best effort only, never gates success
93
+ }
94
+ return true;
95
+ }
96
+
97
+ // ---------------------------------------------------------------------------
98
+ // GuidanceFields — extracted from 4 byte-identical copies
99
+ // ---------------------------------------------------------------------------
100
+
101
+ export interface GuidanceFields {
102
+ promptSnippet?: string;
103
+ promptGuidelines?: string[];
104
+ }
105
+
106
+ // TypeBox form of GuidanceFields. Mirrors the interface 1:1 — same fields,
107
+ // same optionality. `additionalProperties: true` lets consumers compose
108
+ // wrappers that may carry sibling-specific keys without those leaking back
109
+ // into rpiv-config. The runtime invariants (non-empty string, non-empty
110
+ // array of non-empty strings) are still enforced by `validateGuidanceFields`;
111
+ // the schema is a structural type-narrowing aid for callers that bake
112
+ // guidance into a larger TypeBox-validated config object.
113
+ export const GuidanceFieldsSchema = Type.Object(
114
+ {
115
+ promptSnippet: Type.Optional(Type.String()),
116
+ promptGuidelines: Type.Optional(Type.Array(Type.String())),
117
+ },
118
+ { additionalProperties: true },
119
+ );
120
+
121
+ /**
122
+ * Validate and extract guidance fields from an unknown value.
123
+ *
124
+ * Returns a clean `GuidanceFields` object with only valid entries.
125
+ * Byte-identical logic previously in rpiv-todo, rpiv-ask-user-question,
126
+ * rpiv-advisor, and rpiv-web-tools.
127
+ */
128
+ export function validateGuidanceFields(fields: unknown): GuidanceFields {
129
+ if (!fields || typeof fields !== "object") return {};
130
+ const g = fields as Record<string, unknown>;
131
+ const result: GuidanceFields = {};
132
+ if (typeof g.promptSnippet === "string" && g.promptSnippet.length > 0) {
133
+ result.promptSnippet = g.promptSnippet;
134
+ }
135
+ if (
136
+ Array.isArray(g.promptGuidelines) &&
137
+ g.promptGuidelines.length > 0 &&
138
+ g.promptGuidelines.every((s) => typeof s === "string" && s.length > 0)
139
+ ) {
140
+ result.promptGuidelines = g.promptGuidelines;
141
+ }
142
+ return result;
143
+ }
144
+
145
+ // ---------------------------------------------------------------------------
146
+ // Model key codec — provider:id string ↔ { provider, modelId } object.
147
+ // ---------------------------------------------------------------------------
148
+
149
+ /**
150
+ * Parse a model key string into its components.
151
+ *
152
+ * Accepts EITHER separator on read:
153
+ * - "provider/modelId" — canonical form (emitted by modelKey and persisted
154
+ * by post-slash-canonical-migration consumers).
155
+ * - "provider:modelId" — legacy form (persisted by released rpiv-advisor
156
+ * 1.16+ before the migration). Auto-rewritten on the next save by any
157
+ * consumer that re-serialises via modelKey.
158
+ *
159
+ * Slash is preferred when present — a key like "provider:foo/bar" splits on
160
+ * `/`, so the modelId is "bar" rather than re-introducing the legacy
161
+ * interpretation. No current model id contains a `/` so this asymmetry has
162
+ * no real-world ambiguity.
163
+ */
164
+ export function parseModelKey(key: string): { provider: string; modelId: string } | undefined {
165
+ const slashIdx = key.indexOf("/");
166
+ if (slashIdx >= 1) return { provider: key.slice(0, slashIdx), modelId: key.slice(slashIdx + 1) };
167
+ const colonIdx = key.indexOf(":");
168
+ if (colonIdx >= 1) return { provider: key.slice(0, colonIdx), modelId: key.slice(colonIdx + 1) };
169
+ return undefined;
170
+ }
171
+
172
+ /**
173
+ * Compose the canonical "provider/modelId" string from provider and modelId
174
+ * components. Slash-only emission; paired with parseModelKey's tolerant read,
175
+ * legacy colon-form persisted values auto-migrate the next time any consumer
176
+ * re-serialises through this codec.
177
+ */
178
+ export function modelKey(m: { provider: string; id: string }): string {
179
+ return `${m.provider}/${m.id}`;
180
+ }
181
+
182
+ // ---------------------------------------------------------------------------
183
+ // Env-var fallback
184
+ // ---------------------------------------------------------------------------
185
+
186
+ /**
187
+ * Read an environment variable with optional fallback.
188
+ *
189
+ * Trims whitespace from the env value. Returns `fallback` (or `undefined`)
190
+ * when the variable is unset or empty after trimming.
191
+ */
192
+ export function readEnvVar(key: string, fallback?: string): string | undefined {
193
+ return process.env[key]?.trim() || fallback;
194
+ }
195
+
196
+ // ---------------------------------------------------------------------------
197
+ // TypeBox-driven schema validation
198
+ // ---------------------------------------------------------------------------
199
+
200
+ /**
201
+ * Validate and clean a config value against a TypeBox schema.
202
+ *
203
+ * 1. Guards against non-plain-object input (returns `{}` for primitives, arrays).
204
+ * 2. Clones the input (Value.Clean mutates).
205
+ * 3. Strips unknown properties via `Value.Clean`.
206
+ * 4. Applies schema defaults via `Value.Create` (spread merge: defaults
207
+ * provide base, cleaned value overrides).
208
+ * 5. Returns the validated, cleaned object typed as the schema's static type.
209
+ *
210
+ * Falls back to `{}` on any failure — same fail-soft contract as `loadJsonConfig`.
211
+ */
212
+ export function validateConfig<T extends TObject>(schema: T, value: unknown): Static<T> {
213
+ try {
214
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return {} as Static<T>;
215
+ const cleaned = Value.Clean(schema, Value.Clone(value));
216
+ const defaults = Value.Create(schema);
217
+ // Merge: defaults as base, cleaned values override.
218
+ // Both are plain objects from TypeBox operations — safe spread via Record cast.
219
+ return { ...(defaults as Record<string, unknown>), ...(cleaned as Record<string, unknown>) } as Static<T>;
220
+ } catch {
221
+ return {} as Static<T>;
222
+ }
223
+ }
@@ -0,0 +1,12 @@
1
+ export {
2
+ configPath,
3
+ type GuidanceFields,
4
+ GuidanceFieldsSchema,
5
+ loadJsonConfig,
6
+ modelKey,
7
+ parseModelKey,
8
+ readEnvVar,
9
+ saveJsonConfig,
10
+ validateConfig,
11
+ validateGuidanceFields,
12
+ } from "./config.js";
@@ -0,0 +1,65 @@
1
+ /**
2
+ * i18n bridge for rpiv-todo — single thin import surface so every call site
3
+ * routes through one module. Backed by `@juicesharp/rpiv-i18n`'s SDK when
4
+ * available; degrades to canonical-English fallbacks when not.
5
+ *
6
+ * - `t(key, fallback)` is `scope("@juicesharp/rpiv-todo")` if the SDK is
7
+ * installed (live `/languages` updates propagate). If the SDK is missing
8
+ * (standalone install without rpiv-i18n), `t` is an identity passthrough
9
+ * that returns the inline English fallback at every call site, so the
10
+ * extension stays online with English UI.
11
+ * - `formatStatusLabel(status)` resolves a TaskStatus to its locale-aware
12
+ * label via the canonical `status.*` namespace, with the English literal
13
+ * as fallback so nothing renders blank if the namespace isn't registered.
14
+ * This is the SINGLE point of localization for status words — overlay,
15
+ * /todos header, /todos render-call all route through here.
16
+ *
17
+ * Strings are registered ONCE at extension load (see ../index.ts). Call sites
18
+ * MUST use this module at render time — never bake the result into a top-level
19
+ * `const X = formatStatusLabel(...)`.
20
+ */
21
+
22
+ import type { TaskStatus } from "../tool/types.js";
23
+
24
+ export const I18N_NAMESPACE = "@juicesharp/rpiv-todo";
25
+
26
+ type ScopeFn = (key: string, fallback: string) => string;
27
+ type I18nSDK = { scope: (namespace: string) => ScopeFn };
28
+
29
+ // Prefer the live SDK if installed: closures it returns track the active
30
+ // locale, so /languages picker propagates to our render call sites. If the
31
+ // SDK isn't installed (standalone install of this extension without
32
+ // rpiv-i18n), the dynamic import fails, every t(key, fallback) returns the
33
+ // canonical English literal, and the extension stays online.
34
+ //
35
+ // Top-level await is required so a synchronous `t(...)` call from any
36
+ // downstream module sees the resolved scope; ESM module loading awaits this
37
+ // before evaluating any importer.
38
+ let scopeImpl: ScopeFn;
39
+ try {
40
+ const i18nSpecifier: string = "@juicesharp/rpiv-i18n";
41
+ const sdk = (await import(i18nSpecifier)) as I18nSDK;
42
+ scopeImpl = sdk.scope(I18N_NAMESPACE);
43
+ } catch {
44
+ scopeImpl = (_key, fallback) => fallback;
45
+ }
46
+
47
+ export const t: ScopeFn = scopeImpl;
48
+
49
+ const STATUS_LABEL_PENDING = "pending";
50
+ const STATUS_LABEL_IN_PROGRESS = "in progress";
51
+ const STATUS_LABEL_COMPLETED = "completed";
52
+ const STATUS_LABEL_DELETED = "deleted";
53
+
54
+ export function formatStatusLabel(status: TaskStatus): string {
55
+ switch (status) {
56
+ case "pending":
57
+ return t("status.pending", STATUS_LABEL_PENDING);
58
+ case "in_progress":
59
+ return t("status.in_progress", STATUS_LABEL_IN_PROGRESS);
60
+ case "completed":
61
+ return t("status.completed", STATUS_LABEL_COMPLETED);
62
+ case "deleted":
63
+ return t("status.deleted", STATUS_LABEL_DELETED);
64
+ }
65
+ }
@@ -0,0 +1,20 @@
1
+ import type { TaskStatus } from "../tool/types.js";
2
+
3
+ /**
4
+ * Allowed forward transitions per source status. `completed` is one-way to
5
+ * `deleted` (never back to `in_progress`); `deleted` is terminal.
6
+ *
7
+ * Idempotent same→same is checked separately in `isTransitionValid` so this
8
+ * table only enumerates actual transitions.
9
+ */
10
+ export const VALID_TRANSITIONS: Record<TaskStatus, ReadonlySet<TaskStatus>> = {
11
+ pending: new Set(["in_progress", "completed", "deleted"]),
12
+ in_progress: new Set(["pending", "completed", "deleted"]),
13
+ completed: new Set(["deleted"]),
14
+ deleted: new Set(),
15
+ };
16
+
17
+ export function isTransitionValid(from: TaskStatus, to: TaskStatus): boolean {
18
+ if (from === to) return true;
19
+ return VALID_TRANSITIONS[from].has(to);
20
+ }
@@ -0,0 +1,38 @@
1
+ import type { TaskDetails } from "../tool/types.js";
2
+ import { EMPTY_STATE, type TaskState } from "./state.js";
3
+
4
+ /**
5
+ * Discriminator for `details` envelopes that match the persisted `TaskDetails`
6
+ * shape. Defensive — branch entries from older or corrupt sessions are
7
+ * skipped silently.
8
+ */
9
+ export function isTaskDetails(value: unknown): value is TaskDetails {
10
+ if (!value || typeof value !== "object") return false;
11
+ const v = value as Record<string, unknown>;
12
+ return Array.isArray(v.tasks) && typeof v.nextId === "number";
13
+ }
14
+
15
+ /**
16
+ * Walk the current branch in chronological order; the LAST `toolResult` whose
17
+ * `toolName === "todo"` and whose `details` shape matches `TaskDetails` wins
18
+ * (last-write-wins). When no matching entry exists, returns `EMPTY_STATE`.
19
+ *
20
+ * Pure of module state — `index.ts` writes the returned snapshot into the
21
+ * store after this returns. The function explicitly does NOT touch the store
22
+ * cell.
23
+ */
24
+ export function replayFromBranch(ctx: { sessionManager: { getBranch(): Iterable<unknown> } }): TaskState {
25
+ let result: TaskState = { tasks: [...EMPTY_STATE.tasks], nextId: EMPTY_STATE.nextId };
26
+ for (const entry of ctx.sessionManager.getBranch()) {
27
+ const e = entry as { type?: string; message?: { role?: string; toolName?: string; details?: unknown } };
28
+ if (e.type !== "message") continue;
29
+ const msg = e.message;
30
+ if (msg?.role !== "toolResult" || msg.toolName !== "todo") continue;
31
+ if (!isTaskDetails(msg.details)) continue;
32
+ result = {
33
+ tasks: msg.details.tasks.map((t) => ({ ...t })),
34
+ nextId: msg.details.nextId,
35
+ };
36
+ }
37
+ return result;
38
+ }