@selesai/code 0.1.19 → 0.2.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 (157) hide show
  1. package/dist/agents/architect.md +4 -3
  2. package/dist/agents/builder.md +5 -4
  3. package/dist/agents/commentator.md +3 -2
  4. package/dist/agents/explorer.md +4 -4
  5. package/dist/agents/recapper.md +4 -3
  6. package/dist/config.d.ts +6 -7
  7. package/dist/config.d.ts.map +1 -1
  8. package/dist/config.js +7 -9
  9. package/dist/config.js.map +1 -1
  10. package/dist/core/agent-session.d.ts.map +1 -1
  11. package/dist/core/agent-session.js +3 -1
  12. package/dist/core/agent-session.js.map +1 -1
  13. package/dist/core/compaction/compaction.d.ts.map +1 -1
  14. package/dist/core/compaction/compaction.js +18 -24
  15. package/dist/core/compaction/compaction.js.map +1 -1
  16. package/dist/core/extensions/loader.d.ts.map +1 -1
  17. package/dist/core/extensions/loader.js +2 -0
  18. package/dist/core/extensions/loader.js.map +1 -1
  19. package/dist/core/extensions/types.d.ts +8 -1
  20. package/dist/core/extensions/types.d.ts.map +1 -1
  21. package/dist/core/extensions/types.js.map +1 -1
  22. package/dist/core/skills.d.ts.map +1 -1
  23. package/dist/core/skills.js +25 -11
  24. package/dist/core/skills.js.map +1 -1
  25. package/dist/defaults/models.json +143 -39
  26. package/dist/defaults/settings.json +2 -29
  27. package/dist/extensions/package.json +5 -4
  28. package/dist/extensions/pi-intercom/index.ts +12 -5
  29. package/dist/extensions/pi-powerline-footer/index.ts +4 -1
  30. package/dist/extensions/pi-powerline-footer/tps.ts +286 -0
  31. package/dist/extensions/pi-powerline-footer/welcome.ts +47 -46
  32. package/dist/extensions/pi-subagents/README.md +12 -5
  33. package/dist/extensions/pi-subagents/agents/context-builder.md +2 -2
  34. package/dist/extensions/pi-subagents/agents/researcher.md +4 -5
  35. package/dist/extensions/pi-subagents/package.json +8 -5
  36. package/dist/extensions/pi-subagents/prompts/parallel-context-build.md +1 -1
  37. package/dist/extensions/pi-subagents/prompts/parallel-handoff-plan.md +1 -1
  38. package/dist/extensions/pi-subagents/src/agents/agent-management.ts +1 -1
  39. package/dist/extensions/pi-subagents/src/agents/agents.ts +3 -3
  40. package/dist/extensions/pi-subagents/src/extension/control-notices.ts +1 -1
  41. package/dist/extensions/pi-subagents/src/extension/doctor.ts +3 -3
  42. package/dist/extensions/pi-subagents/src/extension/fanout-child.ts +1 -1
  43. package/dist/extensions/pi-subagents/src/extension/index.ts +29 -2
  44. package/dist/extensions/pi-subagents/src/profiles/profiles.ts +2 -2
  45. package/dist/extensions/pi-subagents/src/runs/background/async-execution.ts +72 -13
  46. package/dist/extensions/pi-subagents/src/runs/background/async-job-tracker.ts +1 -1
  47. package/dist/extensions/pi-subagents/src/runs/background/notify.ts +1 -1
  48. package/dist/extensions/pi-subagents/src/runs/background/subagent-runner.ts +85 -41
  49. package/dist/extensions/pi-subagents/src/runs/foreground/chain-clarify.ts +1 -1
  50. package/dist/extensions/pi-subagents/src/runs/foreground/chain-execution.ts +1 -1
  51. package/dist/extensions/pi-subagents/src/runs/foreground/execution.ts +46 -3
  52. package/dist/extensions/pi-subagents/src/runs/foreground/subagent-executor.ts +2 -2
  53. package/dist/extensions/pi-subagents/src/runs/shared/completion-guard.ts +1 -3
  54. package/dist/extensions/pi-subagents/src/runs/shared/nested-events.ts +2 -2
  55. package/dist/extensions/pi-subagents/src/runs/shared/pi-args.ts +18 -18
  56. package/dist/extensions/pi-subagents/src/runs/shared/pi-spawn.ts +24 -24
  57. package/dist/extensions/pi-subagents/src/runs/shared/spawn-timing.ts +46 -0
  58. package/dist/extensions/pi-subagents/src/runs/shared/structured-output.ts +2 -2
  59. package/dist/extensions/pi-subagents/src/runs/shared/subagent-prompt-runtime.ts +4 -4
  60. package/dist/extensions/pi-subagents/src/shared/fork-context.ts +1 -1
  61. package/dist/extensions/pi-subagents/src/shared/types.ts +6 -6
  62. package/dist/extensions/pi-subagents/src/shared/utils.ts +3 -3
  63. package/dist/extensions/pi-subagents/src/slash/slash-bridge.ts +1 -1
  64. package/dist/extensions/pi-subagents/src/slash/slash-commands.ts +1 -1
  65. package/dist/extensions/pi-subagents/src/tui/render-helpers.ts +1 -1
  66. package/dist/extensions/pi-subagents/src/tui/render.ts +1 -1
  67. package/dist/extensions/pi-subagents/test/unit/spawn-timing.test.ts +45 -0
  68. package/dist/extensions/pi-subagents/tsconfig.runner.json +17 -0
  69. package/dist/extensions/pi-web-agent/package.json +31 -0
  70. package/dist/extensions/pi-web-agent/src/backends/config.ts +205 -0
  71. package/dist/extensions/pi-web-agent/src/backends/doctor.ts +136 -0
  72. package/dist/extensions/pi-web-agent/src/backends/factory.ts +152 -0
  73. package/dist/extensions/pi-web-agent/src/backends/settings-reader.ts +25 -0
  74. package/dist/extensions/pi-web-agent/src/cache/ttl-cache.ts +28 -0
  75. package/dist/extensions/pi-web-agent/src/changelog-notice.ts +133 -0
  76. package/dist/extensions/pi-web-agent/src/commands/web-agent-config.ts +946 -0
  77. package/dist/extensions/pi-web-agent/src/extension.ts +126 -0
  78. package/dist/extensions/pi-web-agent/src/extract/readability.ts +118 -0
  79. package/dist/extensions/pi-web-agent/src/fetch/browser-resolution.ts +199 -0
  80. package/dist/extensions/pi-web-agent/src/fetch/firecrawl-fetch.ts +100 -0
  81. package/dist/extensions/pi-web-agent/src/fetch/headless-fetch.ts +117 -0
  82. package/dist/extensions/pi-web-agent/src/fetch/http-fetch.ts +67 -0
  83. package/dist/extensions/pi-web-agent/src/orchestration/answer-synthesizer.ts +60 -0
  84. package/dist/extensions/pi-web-agent/src/orchestration/candidate-selector.ts +50 -0
  85. package/dist/extensions/pi-web-agent/src/orchestration/direct-url.ts +52 -0
  86. package/dist/extensions/pi-web-agent/src/orchestration/evidence-quality.ts +105 -0
  87. package/dist/extensions/pi-web-agent/src/orchestration/evidence-ranker.ts +45 -0
  88. package/dist/extensions/pi-web-agent/src/orchestration/index.ts +28 -0
  89. package/dist/extensions/pi-web-agent/src/orchestration/query-planner.ts +47 -0
  90. package/dist/extensions/pi-web-agent/src/orchestration/research-orchestrator.ts +376 -0
  91. package/dist/extensions/pi-web-agent/src/orchestration/research-types.ts +64 -0
  92. package/dist/extensions/pi-web-agent/src/orchestration/research-worker.ts +181 -0
  93. package/dist/extensions/pi-web-agent/src/orchestration/source-profile.ts +101 -0
  94. package/dist/extensions/pi-web-agent/src/orchestration/stop-decider.ts +81 -0
  95. package/dist/extensions/pi-web-agent/src/presentation/config-store.ts +208 -0
  96. package/dist/extensions/pi-web-agent/src/presentation/config.ts +75 -0
  97. package/dist/extensions/pi-web-agent/src/presentation/explore-presentation.ts +61 -0
  98. package/dist/extensions/pi-web-agent/src/presentation/fetch-presentation.ts +54 -0
  99. package/dist/extensions/pi-web-agent/src/presentation/search-presentation.ts +41 -0
  100. package/dist/extensions/pi-web-agent/src/presentation/select-view.ts +20 -0
  101. package/dist/extensions/pi-web-agent/src/presentation/types.ts +63 -0
  102. package/dist/extensions/pi-web-agent/src/search/brave.ts +114 -0
  103. package/dist/extensions/pi-web-agent/src/search/duckduckgo.ts +72 -0
  104. package/dist/extensions/pi-web-agent/src/search/searxng.ts +96 -0
  105. package/dist/extensions/pi-web-agent/src/tools/web-explore.ts +71 -0
  106. package/dist/extensions/pi-web-agent/src/tools/web-fetch-headless.ts +31 -0
  107. package/dist/extensions/pi-web-agent/src/tools/web-fetch.ts +31 -0
  108. package/dist/extensions/pi-web-agent/src/tools/web-search.ts +157 -0
  109. package/dist/extensions/pi-web-agent/src/types.ts +88 -0
  110. package/dist/extensions/ponytail/index.js +189 -0
  111. package/dist/extensions/ponytail/package.json +8 -0
  112. package/dist/extensions/ponytail/ponytail-config.cjs +122 -0
  113. package/dist/extensions/ponytail/ponytail-instructions.cjs +94 -0
  114. package/dist/extensions/ponytail/test/extension.test.js +167 -0
  115. package/dist/extensions/ponytail/test/helpers.test.js +92 -0
  116. package/dist/extensions/question/constants.ts +38 -0
  117. package/dist/extensions/question/dialog-adapter.ts +74 -0
  118. package/dist/extensions/question/helpers.ts +102 -0
  119. package/dist/extensions/question/index.ts +671 -0
  120. package/dist/extensions/question/navigation.ts +14 -0
  121. package/dist/extensions/question/package.json +18 -0
  122. package/dist/extensions/question/question-list.ts +498 -0
  123. package/dist/extensions/question/row-layout.ts +162 -0
  124. package/dist/extensions/question/schemas.ts +69 -0
  125. package/dist/extensions/question/selection-mode.ts +49 -0
  126. package/dist/extensions/question/shortcuts.ts +53 -0
  127. package/dist/extensions/question/tests/helpers.test.ts +178 -0
  128. package/dist/extensions/question/tests/question-list.test.ts +230 -0
  129. package/dist/extensions/question/tests/row-layout.test.ts +136 -0
  130. package/dist/extensions/question/tests/shortcuts.test.ts +85 -0
  131. package/dist/extensions/question/tests/ui-protocol.test.ts +143 -0
  132. package/dist/extensions/question/tui-adapter.ts +33 -0
  133. package/dist/extensions/question/types.ts +102 -0
  134. package/dist/extensions/question/ui-protocol.ts +46 -0
  135. package/dist/extensions/tokenin-onboarding.ts +265 -2
  136. package/dist/extensions/web-agent-onboarding.ts +222 -0
  137. package/dist/extensions/workflow/adapter.ts +588 -0
  138. package/dist/extensions/workflow/extension.ts +24 -0
  139. package/dist/extensions/workflow/modes/prototype.ts +156 -0
  140. package/dist/extensions/workflow/modes/quick.ts +138 -0
  141. package/dist/extensions/workflow/package.json +17 -0
  142. package/dist/extensions/workflow/state-machine.ts +386 -0
  143. package/dist/index.d.ts +1 -1
  144. package/dist/index.d.ts.map +1 -1
  145. package/dist/index.js +1 -1
  146. package/dist/index.js.map +1 -1
  147. package/dist/modes/interactive/interactive-mode.d.ts +2 -0
  148. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  149. package/dist/modes/interactive/interactive-mode.js +57 -13
  150. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  151. package/dist/utils/mime.d.ts.map +1 -1
  152. package/dist/utils/mime.js +24 -1
  153. package/dist/utils/mime.js.map +1 -1
  154. package/docs/docs.json +4 -0
  155. package/docs/workflows.md +206 -0
  156. package/package.json +5 -1
  157. package/README.md +0 -198
@@ -4,11 +4,15 @@
4
4
  * On the first interactive session, ask the user whether they want to connect a
5
5
  * Token-In token. If yes, open the Token-In dashboard, collect the pasted token,
6
6
  * and persist it in ~/.selesai/agent/models.json under providers.tokenin.apiKey.
7
+ *
8
+ * Slash command `/tokenin <add|switch|remove>` manages multiple TokenIN accounts
9
+ * stored in ~/.selesai/agent/tokenin-auth.json, mirroring the active account into
10
+ * models.json.
7
11
  */
8
12
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
9
13
  import { dirname, join } from "node:path";
10
14
  import { getAgentDir, getModelsPath } from "@earendil-works/pi-coding-agent";
11
- import type { ExtensionAPI, ExtensionContext, SessionStartEvent } from "@earendil-works/pi-coding-agent";
15
+ import type { ExtensionAPI, ExtensionCommandContext, ExtensionContext, SessionStartEvent } from "@earendil-works/pi-coding-agent";
12
16
 
13
17
  export const TOKEN_IN_PROVIDER = "tokenin";
14
18
  export const TOKEN_IN_DASHBOARD_URL = "https://token-in.selesai.in/dashboard/tokens";
@@ -75,6 +79,127 @@ export function validateTokenInToken(raw: string | undefined): { token?: string;
75
79
  return { token: trimmed };
76
80
  }
77
81
 
82
+ // ---------------------------------------------------------------------------
83
+ // tokenin-auth.json — multi-account storage
84
+ // ---------------------------------------------------------------------------
85
+
86
+ export interface TokenInAccount {
87
+ id: string;
88
+ label: string;
89
+ apiKey: string;
90
+ baseUrl?: string;
91
+ }
92
+
93
+ export interface TokenInAuth {
94
+ accounts: TokenInAccount[];
95
+ activeId: string | null;
96
+ }
97
+
98
+ const DEFAULT_AUTH: TokenInAuth = { accounts: [], activeId: null };
99
+
100
+ export function getTokenInAuthPath(agentDir: string = getAgentDir()): string {
101
+ return join(agentDir, "tokenin-auth.json");
102
+ }
103
+
104
+ export function readTokenInAuth(authPath: string = getTokenInAuthPath()): TokenInAuth {
105
+ try {
106
+ const raw = readFileSync(authPath, "utf-8");
107
+ const parsed = JSON.parse(raw) as unknown;
108
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return { ...DEFAULT_AUTH };
109
+ const obj = parsed as Record<string, unknown>;
110
+ const accounts = Array.isArray(obj.accounts) ? (obj.accounts as unknown[]).filter(isTokenInAccount) : [];
111
+ const activeId = typeof obj.activeId === "string" ? obj.activeId : null;
112
+ return { accounts, activeId };
113
+ } catch {
114
+ return { ...DEFAULT_AUTH };
115
+ }
116
+ }
117
+
118
+ function isTokenInAccount(value: unknown): value is TokenInAccount {
119
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
120
+ const v = value as Record<string, unknown>;
121
+ return typeof v.id === "string" && typeof v.apiKey === "string";
122
+ }
123
+
124
+ export function writeTokenInAuth(auth: TokenInAuth, authPath: string = getTokenInAuthPath()): void {
125
+ mkdirSync(dirname(authPath), { recursive: true });
126
+ writeFileSync(authPath, `${JSON.stringify(auth, null, 2)}\n`, "utf-8");
127
+ }
128
+
129
+ function getTokenInBaseUrl(models: Record<string, unknown>): string | undefined {
130
+ const providers = models.providers;
131
+ if (!providers || typeof providers !== "object" || Array.isArray(providers)) return undefined;
132
+ const tokenin = (providers as Record<string, unknown>)[TOKEN_IN_PROVIDER];
133
+ if (!tokenin || typeof tokenin !== "object" || Array.isArray(tokenin)) return undefined;
134
+ const baseUrl = (tokenin as Record<string, unknown>).baseUrl;
135
+ return typeof baseUrl === "string" ? baseUrl : undefined;
136
+ }
137
+
138
+ function makeTokenInLabel(token: string): string {
139
+ const last8 = token.slice(-8);
140
+ return `sk-…${last8}`;
141
+ }
142
+
143
+ /** Upsert an account into tokenin-auth.json. Optionally set it as active. */
144
+ export function saveTokenInAccount(
145
+ token: string,
146
+ options?: { baseUrl?: string; setActive?: boolean },
147
+ authPath: string = getTokenInAuthPath(),
148
+ ): TokenInAuth {
149
+ const auth = readTokenInAuth(authPath);
150
+ const existing = auth.accounts.find((a) => a.id === token);
151
+ const account: TokenInAccount = {
152
+ id: token,
153
+ label: existing?.label ?? makeTokenInLabel(token),
154
+ apiKey: token,
155
+ baseUrl: options?.baseUrl ?? existing?.baseUrl,
156
+ };
157
+ if (!account.baseUrl) delete account.baseUrl;
158
+
159
+ if (existing) {
160
+ Object.assign(existing, account);
161
+ } else {
162
+ auth.accounts.push(account);
163
+ }
164
+
165
+ if (options?.setActive) {
166
+ auth.activeId = token;
167
+ }
168
+
169
+ writeTokenInAuth(auth, authPath);
170
+ return auth;
171
+ }
172
+
173
+ /** Write the given account into models.json and update tokenin-auth activeId. */
174
+ export function applyTokenInAccountToModels(
175
+ account: TokenInAccount,
176
+ modelsPath: string = getModelsPath(),
177
+ authPath: string = getTokenInAuthPath(),
178
+ ): void {
179
+ let updated = setTokenInApiKey(readModelsJson(modelsPath), account.apiKey);
180
+ if (account.baseUrl) {
181
+ const providers = updated.providers as Record<string, unknown>;
182
+ const tokenin = providers[TOKEN_IN_PROVIDER] as Record<string, unknown>;
183
+ tokenin.baseUrl = account.baseUrl;
184
+ }
185
+ writeModelsJson(updated, modelsPath);
186
+
187
+ const auth = readTokenInAuth(authPath);
188
+ auth.activeId = account.id;
189
+ writeTokenInAuth(auth, authPath);
190
+ }
191
+
192
+ /** Return the id of the account whose apiKey matches models.json, or null. */
193
+ export function getActiveTokenInAccountId(
194
+ modelsPath: string = getModelsPath(),
195
+ authPath: string = getTokenInAuthPath(),
196
+ ): string | null {
197
+ const apiKey = getTokenInApiKey(readModelsJson(modelsPath));
198
+ if (typeof apiKey !== "string") return null;
199
+ const auth = readTokenInAuth(authPath);
200
+ return auth.accounts.find((a) => a.apiKey === apiKey)?.id ?? null;
201
+ }
202
+
78
203
  function getOnboardingMarkerPath(agentDir: string = getAgentDir()): string {
79
204
  return join(agentDir, ONBOARDING_MARKER_NAME);
80
205
  }
@@ -111,6 +236,123 @@ async function promptForToken(ctx: ExtensionContext): Promise<string | undefined
111
236
  return ctx.ui.input("Paste your Token-In token", "sk-...");
112
237
  }
113
238
 
239
+ // ---------------------------------------------------------------------------
240
+ // /tokenin subcommand handlers
241
+ // ---------------------------------------------------------------------------
242
+
243
+ async function handleTokenInAdd(pi: ExtensionAPI, ctx: ExtensionCommandContext): Promise<void> {
244
+ if (!ctx.hasUI) {
245
+ ctx.ui.notify("This command requires interactive mode.", "warning");
246
+ return;
247
+ }
248
+
249
+ try {
250
+ await openDashboard(pi);
251
+ ctx.ui.notify("Opened Token-In dashboard in your browser.", "info");
252
+ } catch (err) {
253
+ const message = err instanceof Error ? err.message : String(err);
254
+ ctx.ui.notify(`Could not open browser: ${message}`, "warning");
255
+ ctx.ui.notify(`Open this URL manually: ${TOKEN_IN_DASHBOARD_URL}`, "info");
256
+ }
257
+
258
+ const rawToken = await promptForToken(ctx);
259
+ const validated = validateTokenInToken(rawToken);
260
+ if (validated.error) {
261
+ ctx.ui.notify(validated.error, "warning");
262
+ return;
263
+ }
264
+
265
+ const token = validated.token!;
266
+ const models = readModelsJson();
267
+ const baseUrl = getTokenInBaseUrl(models);
268
+ const auth = readTokenInAuth();
269
+ const wasEmpty = auth.accounts.length === 0;
270
+
271
+ saveTokenInAccount(token, { baseUrl });
272
+
273
+ if (wasEmpty) {
274
+ const saved = readTokenInAuth().accounts.find((a) => a.id === token)!;
275
+ applyTokenInAccountToModels(saved);
276
+ try {
277
+ ctx.modelRegistry.refresh();
278
+ } catch {
279
+ // best-effort
280
+ }
281
+ ctx.ui.notify(`Token-In token saved and activated (${saved.label}).`, "info");
282
+ } else {
283
+ ctx.ui.notify("Account added. Use /tokenin switch to activate it.", "info");
284
+ }
285
+ }
286
+
287
+ // ponytail: ctx.ui.select returns the label string, not an index. We match by
288
+ // indexOf on the labels array — if two accounts share the same last-8 suffix
289
+ // the first match wins. Acceptable for this use case; upgrade to indexed select
290
+ // if multi-account collisions become common.
291
+ async function pickAccount(
292
+ ctx: ExtensionCommandContext,
293
+ title: string,
294
+ auth: TokenInAuth,
295
+ ): Promise<TokenInAccount | undefined> {
296
+ const labels = auth.accounts.map((a) => a.label);
297
+ const selected = await ctx.ui.select(title, labels);
298
+ if (selected === undefined) return undefined;
299
+ const index = labels.indexOf(selected);
300
+ return auth.accounts[index];
301
+ }
302
+
303
+ async function handleTokenInSwitch(ctx: ExtensionCommandContext): Promise<void> {
304
+ if (!ctx.hasUI) {
305
+ ctx.ui.notify("This command requires interactive mode.", "warning");
306
+ return;
307
+ }
308
+
309
+ const auth = readTokenInAuth();
310
+ if (auth.accounts.length === 0) {
311
+ ctx.ui.notify("No saved accounts. Use /tokenin add first.", "warning");
312
+ return;
313
+ }
314
+
315
+ const account = await pickAccount(ctx, "Select TokenIN account", auth);
316
+ if (!account) return;
317
+
318
+ applyTokenInAccountToModels(account);
319
+ try {
320
+ ctx.modelRegistry.refresh();
321
+ } catch {
322
+ // best-effort
323
+ }
324
+ ctx.ui.notify(`Switched to account ${account.label}.`, "info");
325
+ }
326
+
327
+ async function handleTokenInRemove(ctx: ExtensionCommandContext): Promise<void> {
328
+ if (!ctx.hasUI) {
329
+ ctx.ui.notify("This command requires interactive mode.", "warning");
330
+ return;
331
+ }
332
+
333
+ const auth = readTokenInAuth();
334
+ if (auth.accounts.length === 0) {
335
+ ctx.ui.notify("No saved accounts. Use /tokenin add first.", "warning");
336
+ return;
337
+ }
338
+
339
+ const account = await pickAccount(ctx, "Select account to remove", auth);
340
+ if (!account) return;
341
+
342
+ const activeId = getActiveTokenInAccountId();
343
+ if (account.id === activeId) {
344
+ ctx.ui.notify("Cannot remove the active account. Use /tokenin switch first.", "warning");
345
+ return;
346
+ }
347
+
348
+ const confirmed = await ctx.ui.confirm("Remove account?", `Remove account ${account.label}?`);
349
+ if (!confirmed) return;
350
+
351
+ auth.accounts = auth.accounts.filter((a) => a.id !== account.id);
352
+ writeTokenInAuth(auth);
353
+ ctx.ui.notify("Account removed.", "info");
354
+ }
355
+
114
356
  async function runOnboarding(pi: ExtensionAPI, ctx: ExtensionContext): Promise<void> {
115
357
  const modelsPath = getModelsPath();
116
358
  const models = readModelsJson(modelsPath);
@@ -156,10 +398,14 @@ async function runOnboarding(pi: ExtensionAPI, ctx: ExtensionContext): Promise<v
156
398
  return;
157
399
  }
158
400
 
159
- const updated = setTokenInApiKey(models, validated.token!);
401
+ const token = validated.token!;
402
+ const updated = setTokenInApiKey(models, token);
160
403
  writeModelsJson(updated, modelsPath);
161
404
  markOnboardingComplete();
162
405
 
406
+ // Seed tokenin-auth.json so /tokenin switch and /tokenin remove work after onboarding.
407
+ saveTokenInAccount(token, { baseUrl: getTokenInBaseUrl(updated), setActive: true });
408
+
163
409
  // Refresh the in-memory model registry so the key is active immediately.
164
410
  try {
165
411
  ctx.modelRegistry.refresh();
@@ -180,4 +426,21 @@ export default function tokenInOnboardingExtension(pi: ExtensionAPI): void {
180
426
 
181
427
  await runOnboarding(pi, ctx);
182
428
  });
429
+
430
+ pi.registerCommand("tokenin", {
431
+ description: "Manage TokenIN accounts: /tokenin add|switch|remove",
432
+ handler: async (args: string, ctx: ExtensionCommandContext) => {
433
+ await ctx.waitForIdle();
434
+ const sub = args.trim().split(/\s+/)[0];
435
+ if (sub === "add") {
436
+ await handleTokenInAdd(pi, ctx);
437
+ } else if (sub === "switch") {
438
+ await handleTokenInSwitch(ctx);
439
+ } else if (sub === "remove") {
440
+ await handleTokenInRemove(ctx);
441
+ } else {
442
+ ctx.ui.notify("Usage: /tokenin add|switch|remove", "info");
443
+ }
444
+ },
445
+ });
183
446
  }
@@ -0,0 +1,222 @@
1
+ /**
2
+ * Web-Agent first-run onboarding extension.
3
+ *
4
+ * On the first interactive session, ask the user whether they want to use Brave
5
+ * Search. If yes, open the Brave API key dashboard, collect the pasted key, and
6
+ * persist it in ~/.selesai/agent/settings.json under webAgent.braveApiKey, then
7
+ * configure the bundled pi-web-agent backend to use Brave (with DuckDuckGo fallback).
8
+ * If no, the extension falls back to pi-web-agent's default DuckDuckGo backend.
9
+ *
10
+ * Mirrors src/extensions/tokenin-onboarding.ts.
11
+ */
12
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
13
+ import { dirname, join } from "node:path";
14
+ import { getAgentDir, getSettingsPath } from "@earendil-works/pi-coding-agent";
15
+ import type { ExtensionAPI, ExtensionCommandContext, ExtensionContext, SessionStartEvent } from "@earendil-works/pi-coding-agent";
16
+
17
+ export type OnboardingResult =
18
+ | { kind: "saved" }
19
+ | { kind: "skipped" }
20
+ | { kind: "deferred" }
21
+ | { kind: "error"; message: string };
22
+
23
+ export const BRAVE_KEYS_URL = "https://api-dashboard.search.brave.com/app/keys";
24
+ export const ONBOARDING_MARKER_NAME = ".webAgentOnboardingComplete";
25
+ export const WEB_AGENT_CONFIG_SUBPATH = join("extensions", "pi-web-agent", "config.json");
26
+
27
+ // ponytail: duplicated ~15 lines of marker-file + browser-open logic from
28
+ // tokenin-onboarding.ts rather than extracting a shared module nobody asked for.
29
+ // Ceiling: if a third onboarding extension appears, extract a shared helper then.
30
+
31
+ /** Read and parse the current settings.json, returning a deep-ish mutable object. */
32
+ export function readSettingsJson(settingsPath: string = getSettingsPath()): Record<string, unknown> {
33
+ try {
34
+ const raw = readFileSync(settingsPath, "utf-8");
35
+ return JSON.parse(raw) as Record<string, unknown>;
36
+ } catch {
37
+ return {};
38
+ }
39
+ }
40
+
41
+ /** Write settings.json back to disk atomically-ish with a trailing newline. */
42
+ export function writeSettingsJson(settings: Record<string, unknown>, settingsPath: string = getSettingsPath()): void {
43
+ mkdirSync(dirname(settingsPath), { recursive: true });
44
+ writeFileSync(settingsPath, `${JSON.stringify(settings, null, 2)}\n`, "utf-8");
45
+ }
46
+
47
+ /**
48
+ * Return true if the Brave key value is missing, empty. We prompt again for any
49
+ * non-key value.
50
+ */
51
+ export function isPlaceholderKey(apiKey: unknown): boolean {
52
+ if (apiKey === undefined || apiKey === null) return true;
53
+ if (typeof apiKey !== "string") return true;
54
+ return apiKey.trim() === "";
55
+ }
56
+
57
+ /** Return the current webAgent.braveApiKey value from settings.json. */
58
+ export function getBraveApiKey(settings: Record<string, unknown>): unknown {
59
+ const webAgent = settings.webAgent;
60
+ if (!webAgent || typeof webAgent !== "object" || Array.isArray(webAgent)) return undefined;
61
+ return (webAgent as Record<string, unknown>).braveApiKey;
62
+ }
63
+
64
+ /** Return a new settings object with webAgent.braveApiKey set to key. */
65
+ export function setBraveApiKey(settings: Record<string, unknown>, key: string): Record<string, unknown> {
66
+ const next = JSON.parse(JSON.stringify(settings)) as Record<string, unknown>;
67
+ if (!next.webAgent || typeof next.webAgent !== "object" || Array.isArray(next.webAgent)) {
68
+ next.webAgent = {};
69
+ }
70
+ const webAgent = next.webAgent as Record<string, unknown>;
71
+ webAgent.braveApiKey = key;
72
+ return next;
73
+ }
74
+
75
+ /** Validate a pasted Brave key. Returns normalized key or an error message. */
76
+ export function validateBraveKey(raw: string | undefined): { key?: string; error?: string } {
77
+ if (raw === undefined || raw === null) return { error: "No key entered." };
78
+ const trimmed = raw.trim();
79
+ if (trimmed === "") return { error: "Key cannot be empty." };
80
+ return { key: trimmed };
81
+ }
82
+
83
+ /** Path to the pi-web-agent global backend config (matches vendored config-store). */
84
+ export function getWebAgentConfigPath(agentDir: string = getAgentDir()): string {
85
+ return join(agentDir, WEB_AGENT_CONFIG_SUBPATH);
86
+ }
87
+
88
+ /** Write pi-web-agent backend config selecting brave (with duckduckgo fallback). */
89
+ export function writeWebAgentBraveBackendConfig(agentDir: string = getAgentDir()): void {
90
+ const configPath = getWebAgentConfigPath(agentDir);
91
+ mkdirSync(dirname(configPath), { recursive: true });
92
+ // Merge into any existing config so we don't clobber presentation settings.
93
+ let existing: Record<string, unknown> = {};
94
+ try {
95
+ existing = JSON.parse(readFileSync(configPath, "utf-8")) as Record<string, unknown>;
96
+ } catch {
97
+ // ENOENT or invalid JSON — start fresh.
98
+ }
99
+ const next = existing;
100
+ const backends = (next.backends ?? {}) as Record<string, unknown>;
101
+ (backends as Record<string, unknown>).search = { provider: "brave", fallback: "duckduckgo" };
102
+ next.backends = backends;
103
+ writeFileSync(configPath, `${JSON.stringify(next, null, 2)}\n`, "utf-8");
104
+ }
105
+
106
+ function getOnboardingMarkerPath(agentDir: string = getAgentDir()): string {
107
+ return join(agentDir, ONBOARDING_MARKER_NAME);
108
+ }
109
+
110
+ function markOnboardingComplete(agentDir: string = getAgentDir()): void {
111
+ writeFileSync(getOnboardingMarkerPath(agentDir), "1", "utf-8");
112
+ }
113
+
114
+ function isOnboardingComplete(agentDir: string = getAgentDir()): boolean {
115
+ return existsSync(getOnboardingMarkerPath(agentDir));
116
+ }
117
+
118
+ async function openBraveKeysUrl(pi: ExtensionAPI): Promise<void> {
119
+ const url = BRAVE_KEYS_URL;
120
+ let command: string;
121
+ let args: string[];
122
+ if (process.platform === "darwin") {
123
+ command = "open";
124
+ args = [url];
125
+ } else if (process.platform === "win32") {
126
+ command = "cmd";
127
+ args = ["/c", "start", "", url];
128
+ } else {
129
+ command = "xdg-open";
130
+ args = [url];
131
+ }
132
+ const result = await pi.exec(command, args, { timeout: 10_000 });
133
+ if (result.code !== 0) {
134
+ throw new Error(`Failed to open ${url}: ${result.stderr || result.stdout || "unknown error"}`);
135
+ }
136
+ }
137
+
138
+ async function promptForKey(ctx: ExtensionContext): Promise<string | undefined> {
139
+ return ctx.ui.input("Paste your Brave API key", "");
140
+ }
141
+
142
+ async function runOnboarding(pi: ExtensionAPI, ctx: ExtensionContext): Promise<OnboardingResult> {
143
+ const settingsPath = getSettingsPath();
144
+ const settings = readSettingsJson(settingsPath);
145
+ const currentKey = getBraveApiKey(settings);
146
+
147
+ // Already configured? Mark complete and skip.
148
+ if (!isPlaceholderKey(currentKey)) {
149
+ markOnboardingComplete();
150
+ return { kind: "deferred" };
151
+ }
152
+
153
+ // No UI? Defer to a later session.
154
+ if (!ctx.hasUI) {
155
+ return { kind: "deferred" };
156
+ }
157
+
158
+ const wantsBrave = await ctx.ui.confirm(
159
+ "Use Brave Search?",
160
+ "Brave gives reliable web results for the web_explore tool. You can get an API key at https://api-dashboard.search.brave.com/app/keys. Use Brave now?",
161
+ );
162
+
163
+ if (!wantsBrave) {
164
+ markOnboardingComplete();
165
+ ctx.ui.notify("Brave skipped — web search will use the default DuckDuckGo backend.", "info");
166
+ return { kind: "skipped" };
167
+ }
168
+
169
+ try {
170
+ await openBraveKeysUrl(pi);
171
+ ctx.ui.notify("Opened the Brave API key dashboard in your browser.", "info");
172
+ } catch (err) {
173
+ const message = err instanceof Error ? err.message : String(err);
174
+ ctx.ui.notify(`Could not open browser: ${message}`, "warning");
175
+ ctx.ui.notify(`Open this URL manually: ${BRAVE_KEYS_URL}`, "info");
176
+ }
177
+
178
+ const rawKey = await promptForKey(ctx);
179
+ const validated = validateBraveKey(rawKey);
180
+
181
+ if (validated.error) {
182
+ ctx.ui.notify(validated.error, "warning");
183
+ // Do not mark complete so the prompt retries on next launch.
184
+ return { kind: "deferred" };
185
+ }
186
+
187
+ const updated = setBraveApiKey(settings, validated.key!);
188
+ writeSettingsJson(updated, settingsPath);
189
+ // Select Brave as the pi-web-agent search backend (DuckDuckGo fallback).
190
+ writeWebAgentBraveBackendConfig();
191
+ markOnboardingComplete();
192
+
193
+ ctx.ui.notify("Brave API key saved — web search will use Brave.", "info");
194
+ return { kind: "saved" };
195
+ }
196
+
197
+ export default function webAgentOnboardingExtension(pi: ExtensionAPI): void {
198
+ pi.on("session_start", async (event: SessionStartEvent, ctx: ExtensionContext) => {
199
+ if (event.reason !== "startup") return;
200
+ if (isOnboardingComplete()) return;
201
+
202
+ // Avoid prompting during tests or non-interactive runs.
203
+ if (process.env.SELESAI_SKIP_WEB_AGENT_ONBOARDING === "1") return;
204
+
205
+ await runOnboarding(pi, ctx);
206
+ });
207
+
208
+ // ponytail: command reuses runOnboarding() instead of duplicating the flow.
209
+ // On "saved" -> ctx.reload() so pi-web-agent re-applies the Brave backend config.
210
+ // On skipped/deferred -> no reload (nothing changed). The post-reload session_start
211
+ // fires with reason "reload" but the auto handler only acts on "startup", so no double prompt.
212
+ pi.registerCommand("setup-web-search", {
213
+ description: "Re-run the Brave Search onboarding flow, then reload extensions",
214
+ handler: async (_args: string, ctx: ExtensionCommandContext) => {
215
+ const result = await runOnboarding(pi, ctx);
216
+ if (result.kind === "saved") {
217
+ ctx.ui.notify("Brave key saved — reloading extensions…", "info");
218
+ await ctx.reload();
219
+ }
220
+ },
221
+ });
222
+ }