@ycodium-ai/plugin-api 0.2.6027 → 0.2.6072

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 (48) hide show
  1. package/README.md +10 -2
  2. package/dist/_private/ycodium-ui-hooks/ProviderSignInChallenge.d.ts +1 -1
  3. package/dist/_private/ycodium-ui-hooks/ProviderSignInChallenge.js +1 -1
  4. package/dist/conversation-queue.d.ts +1 -0
  5. package/dist/conversation-queue.d.ts.map +1 -1
  6. package/dist/conversation.d.ts +31 -44
  7. package/dist/conversation.d.ts.map +1 -1
  8. package/dist/conversation.js.map +1 -1
  9. package/dist/conversationHostModels.d.ts +2 -0
  10. package/dist/conversationHostModels.d.ts.map +1 -1
  11. package/dist/conversationWorkEntry.d.ts +1 -0
  12. package/dist/conversationWorkEntry.d.ts.map +1 -1
  13. package/dist/dataPorts.gen.d.ts +461 -6
  14. package/dist/dataPorts.gen.d.ts.map +1 -1
  15. package/dist/dataPorts.gen.js.map +1 -1
  16. package/dist/entity-names.d.ts +1 -0
  17. package/dist/entity-names.d.ts.map +1 -1
  18. package/dist/executor.d.ts +8 -4
  19. package/dist/executor.d.ts.map +1 -1
  20. package/dist/executor.js.map +1 -1
  21. package/dist/executorCapabilities.d.ts +2 -0
  22. package/dist/executorCapabilities.d.ts.map +1 -1
  23. package/dist/executorCard.d.ts +6 -0
  24. package/dist/executorCard.d.ts.map +1 -1
  25. package/dist/executorCard.js.map +1 -1
  26. package/dist/runtime-maintenance.d.ts +46 -0
  27. package/dist/runtime-maintenance.d.ts.map +1 -1
  28. package/dist/runtime-maintenance.js +317 -31
  29. package/dist/runtime-maintenance.js.map +1 -1
  30. package/dist/source/_private/ycodium-ui-hooks/ProviderSignInChallenge.tsx +21 -20
  31. package/dist/source/conversation-queue.ts +1 -0
  32. package/dist/source/conversation.ts +30 -37
  33. package/dist/source/conversationHostModels.ts +6 -1
  34. package/dist/source/conversationWorkEntry.ts +1 -0
  35. package/dist/source/dataPorts.gen.ts +54 -36
  36. package/dist/source/entity-names.ts +1 -0
  37. package/dist/source/executor.ts +8 -3
  38. package/dist/source/executorCapabilities.ts +2 -0
  39. package/dist/source/executorCard.ts +7 -0
  40. package/dist/source/runtime-maintenance.ts +413 -33
  41. package/dist/source/ui.ts +6 -1
  42. package/dist/source/version.ts +2 -2
  43. package/dist/ui.d.ts +1 -1
  44. package/dist/ui.d.ts.map +1 -1
  45. package/dist/version.d.ts +2 -2
  46. package/dist/version.d.ts.map +1 -1
  47. package/dist/version.js +1 -1
  48. package/package.json +7 -7
@@ -39,6 +39,7 @@ export interface PluginUiThreadNameProps {
39
39
 
40
40
  /** 插件:门面图标 + 插件显示名(随界面语言),按 id 在所在机器上查。 */
41
41
  export interface PluginUiPluginNameProps {
42
+ readonly entryId?: string | undefined;
42
43
  readonly environmentId: string | null;
43
44
  readonly pluginId: string;
44
45
  readonly fallbackName?: string | undefined;
@@ -26,7 +26,7 @@ import { raceAbort as raceAbortWithSignal } from "./_private/ycodium-executor-co
26
26
  import type { ExecutorRuntimeMode } from "./executorCapabilities.ts";
27
27
  import type { ExecutorLiveProcess, ExecutorOpenCommands } from "./executorProcesses.ts";
28
28
  import type { ExecutorUsage } from "./usage.ts";
29
- import type { ExecutorCard } from "./executorCard.ts";
29
+ import type { ExecutorCard, ExecutorSignInInteraction } from "./executorCard.ts";
30
30
  import type {
31
31
  ExecutorMcpServer,
32
32
  ExecutorProbeResult,
@@ -61,6 +61,7 @@ export type * from "./executorErrors.ts";
61
61
  export type {
62
62
  ExecutorMcpTransport,
63
63
  ExecutorInstall,
64
+ ExecutorSignInInteraction,
64
65
  ExecutorSignInMethod,
65
66
  ExecutorHomeLayout,
66
67
  ExecutorResumeCommand,
@@ -457,14 +458,18 @@ export type ExecutorInstance = {
457
458
  readonly signInCommandUnsetEnv?: readonly string[];
458
459
  /** CLI 登录命令使用的实例账户环境,与实例的会话和探测使用同一套路径。 */
459
460
  readonly signInCommandEnv?: Readonly<Record<string, string>>;
461
+ /** 实例级手动登录说明(如附带本实例凭据目录环境变量的命令);缺省沿用名片的 `signIn`。 */
462
+ readonly signInMethods?: ExecutorCard["signIn"];
460
463
  readonly signIn?: {
461
- /** 授权码由用户在提供方设置区块提交给 CLI,设备码由用户在厂商网页输入。默认设备码。 */
462
- readonly interaction?: "device-code" | "authorization-code";
464
+ /** 授权码由用户在设置中填回,设备码由用户在厂商网页输入,browser 由 CLI 无头轮询网页授权完成。默认设备码。 */
465
+ readonly interaction?: ExecutorSignInInteraction;
463
466
  readonly start: (signal?: AbortSignal) => Promise<{
464
467
  readonly operationId: string;
465
468
  readonly userCode?: string;
466
469
  readonly verificationUrl?: string;
467
470
  }>;
471
+ /** 将用户在授权页拿到的授权码或完整回调地址交给本次登录。格式有误时直接抛错,登录保持等待供重填。 */
472
+ readonly submit?: (operationId: string, code: string, signal?: AbortSignal) => Promise<void>;
468
473
  readonly cancel: (operationId: string, signal?: AbortSignal) => Promise<void>;
469
474
  readonly verify: (signal?: AbortSignal) => Promise<ExecutorProbeResult>;
470
475
  };
@@ -81,6 +81,8 @@ export type ExecutorCapabilities = {
81
81
  * 内置或自带工具搜索的执行器可显式标为 `"full"`。
82
82
  */
83
83
  readonly hostMcpToolListing?: ExecutorHostMcpToolListing;
84
+ /** 由宿主向本机会话提供本轮任务清单工具。原生计划优先。 */
85
+ readonly hostTaskList?: boolean;
84
86
  /** 缺席 = 这只手不收内联图片,或不知道上限:所有图片都只给路径。 */
85
87
  readonly inlineImages?: ExecutorInlineImageLimits;
86
88
  };
@@ -19,6 +19,8 @@ export type ExecutorInstall =
19
19
  | { readonly kind: "npm" }
20
20
  | { readonly kind: "downloadPage"; readonly url: string };
21
21
 
22
+ export type ExecutorSignInInteraction = "device-code" | "authorization-code" | "browser";
23
+
22
24
  export type ExecutorSignInMethod =
23
25
  | { readonly kind: "device-code" }
24
26
  | { readonly kind: "command"; readonly command: string }
@@ -249,6 +251,11 @@ export type ExecutorCard = {
249
251
  readonly environment: ReadonlyArray<{ readonly name: string; readonly sensitive: boolean }>;
250
252
  readonly install: ExecutorInstall | null;
251
253
  readonly signIn: ReadonlyArray<ExecutorSignInMethod>;
254
+ /**
255
+ * 宿主托管一键登录的交互协议(与 `ExecutorInstance.signIn.interaction` 同源)。
256
+ * 仅在实现了产出 `verificationUrl` 的 `ExecutorInstance.signIn` 时声明,供尚无实例快照的向导判断是否准备授权页。
257
+ */
258
+ readonly signInInteraction?: ExecutorSignInInteraction;
252
259
  readonly deviceCodeSignInArgs: ReadonlyArray<string>;
253
260
  readonly npmPackage: string;
254
261
  readonly homebrewFormula: string;
@@ -1,5 +1,6 @@
1
1
  // @effect-diagnostics nodeBuiltinImport:off globalTimers:off - 服务器上的插件共用下载校验与登录期限。
2
2
  import * as NodeCrypto from "node:crypto";
3
+ import * as NodeFS from "node:fs";
3
4
  import * as NodeFSP from "node:fs/promises";
4
5
  import * as NodePath from "node:path";
5
6
  import * as NodeStream from "node:stream";
@@ -135,6 +136,76 @@ export function createSignInLifetime(options: {
135
136
  };
136
137
  }
137
138
 
139
+ const WINDOWS_LOCKED_DIRECTORY_CODES = new Set(["EPERM", "EBUSY", "EACCES"]);
140
+
141
+ function isWindowsLockedDirectoryError(error: unknown, platform: NodeJS.Platform): boolean {
142
+ return (
143
+ platform === "win32" &&
144
+ error instanceof Error &&
145
+ "code" in error &&
146
+ WINDOWS_LOCKED_DIRECTORY_CODES.has(String(error.code))
147
+ );
148
+ }
149
+
150
+ async function copyRuntimeTree(
151
+ source: string,
152
+ destination: string,
153
+ signal: AbortSignal | undefined,
154
+ ): Promise<void> {
155
+ signal?.throwIfAborted();
156
+ const entries = await NodeFSP.readdir(source, { withFileTypes: true });
157
+ for (const entry of entries) {
158
+ signal?.throwIfAborted();
159
+ const from = NodePath.join(source, entry.name);
160
+ const to = NodePath.join(destination, entry.name);
161
+ if (entry.isDirectory()) {
162
+ await NodeFSP.mkdir(to);
163
+ await copyRuntimeTree(from, to, signal);
164
+ } else if (entry.isFile()) {
165
+ await NodeFSP.copyFile(from, to, NodeFS.constants.COPYFILE_EXCL);
166
+ } else if (entry.isSymbolicLink()) {
167
+ await NodeFSP.symlink(await NodeFSP.readlink(from), to);
168
+ } else {
169
+ throw new Error(`Unsupported runtime staging entry: ${entry.name}`);
170
+ }
171
+ }
172
+ }
173
+
174
+ /**
175
+ * 将已校验的暂存版本目录原子发布到正式位置。
176
+ * Windows 在体检进程退出后可能仍由系统或扫描器短暂握住文件句柄,拒绝移动其父目录;
177
+ * 遇到 EPERM / EBUSY / EACCES 时组装一份未运行过的同盘副本,仍以单次 rename 发布完整目录。
178
+ */
179
+ export async function publishRuntimeDirectory(input: {
180
+ readonly source: string;
181
+ readonly destination: string;
182
+ readonly platform: NodeJS.Platform;
183
+ readonly stagingDirectory?: string | undefined;
184
+ readonly signal?: AbortSignal | undefined;
185
+ }): Promise<void> {
186
+ input.signal?.throwIfAborted();
187
+ try {
188
+ await NodeFSP.rename(input.source, input.destination);
189
+ return;
190
+ } catch (error) {
191
+ if (!isWindowsLockedDirectoryError(error, input.platform)) throw error;
192
+ }
193
+
194
+ const parent = input.stagingDirectory ?? NodePath.dirname(input.destination);
195
+ const copy = await NodeFSP.mkdtemp(NodePath.join(parent, ".publish-"));
196
+ let published = false;
197
+ try {
198
+ await copyRuntimeTree(input.source, copy, input.signal);
199
+ input.signal?.throwIfAborted();
200
+ await NodeFSP.rename(copy, input.destination);
201
+ published = true;
202
+ } finally {
203
+ if (!published) {
204
+ await NodeFSP.rm(copy, { recursive: true, force: true }).catch(() => undefined);
205
+ }
206
+ }
207
+ }
208
+
138
209
  /** 安装器已验证并发布版本目录后,原子切换生效记录。写入失败保留上一份记录。 */
139
210
  export async function activateRuntimeRelease(activeFile: string, releaseId: string): Promise<void> {
140
211
  const directory = NodePath.dirname(activeFile);
@@ -164,124 +235,332 @@ const OUTPUT_QUIET_MS = 3_000;
164
235
  const SILENT_CAP_MS = 30_000;
165
236
 
166
237
  /**
167
- * `drained` 在进程输出读完时完成;`code` 在以下任一出路时给出:认出网址与验证码、进程退了、
238
+ * `drained` 在进程输出读完时完成;`challenge` 在以下任一出路时给出:认出登录挑战、进程退了、
168
239
  * 输出停了一阵、一直不出声到封顶。等待按「输出停了多久」算而不按起进程算:满载时进程起得慢,
169
240
  * 起手时间不能吃掉这段窗口。
170
241
  */
171
- function readDeviceCodeOutput(
242
+ const NO_BROWSER_SENTINEL = "__ycodium_no_browser__";
243
+ const ANSI_ESCAPE_SEQUENCES =
244
+ /\u001B\][^\u0007\u001B]*(?:\u0007|\u001B\\)|\u001B\[[0-9;]*[A-Za-z]/gu;
245
+
246
+ const NODE_BROWSER_SUPPRESSION_PRELOAD =
247
+ "data:text/javascript;base64," +
248
+ Buffer.from(
249
+ [
250
+ 'import cp from "node:child_process";',
251
+ 'import { syncBuiltinESMExports } from "node:module";',
252
+ "const hasHttpOrStart = (text) => typeof text === 'string' && (/https?:\\/\\//i.test(text) || /\\bstart-process\\b/i.test(text));",
253
+ "const decodePsEncoded = (argv) => {",
254
+ " for (let i = 0; i < argv.length - 1; i++) {",
255
+ " if (/^-(?:e|ec|enc|encodedcommand)$/i.test(String(argv[i]))) {",
256
+ " try { return Buffer.from(String(argv[i + 1]), 'base64').toString('utf16le'); } catch { return ''; }",
257
+ " }",
258
+ " }",
259
+ " return '';",
260
+ "};",
261
+ "const isBrowserOpen = (file, args) => {",
262
+ " const argv = Array.isArray(args) ? args.map(String) : [];",
263
+ " const base = String(file).replace(/^.*[\\\\/]/, '').toLowerCase();",
264
+ " if ((base === 'cmd' || base === 'cmd.exe') && argv[0]?.toLowerCase() === '/c' && argv[1]?.toLowerCase() === 'start') return argv.some(hasHttpOrStart);",
265
+ " if (base === 'powershell' || base === 'powershell.exe' || base === 'pwsh' || base === 'pwsh.exe') {",
266
+ " return argv.some(hasHttpOrStart) || hasHttpOrStart(decodePsEncoded(argv));",
267
+ " }",
268
+ " if (base === 'open' || base === 'xdg-open' || base === 'gio' || base === 'sensible-browser' || base === 'wslview' || base === 'rundll32' || base === 'rundll32.exe' || base === 'explorer' || base === 'explorer.exe') {",
269
+ " return argv.some(hasHttpOrStart);",
270
+ " }",
271
+ " return false;",
272
+ "};",
273
+ "const origExecFile = cp.execFile;",
274
+ "const origSpawn = cp.spawn;",
275
+ "const origExec = cp.exec;",
276
+ "cp.execFile = function(file, args, options, callback) {",
277
+ " if (isBrowserOpen(file, args)) {",
278
+ " const cb = typeof args === 'function' ? args : typeof options === 'function' ? options : callback;",
279
+ " if (typeof cb === 'function') queueMicrotask(() => cb(null, '', ''));",
280
+ " return origExecFile.call(this, process.execPath, ['-e', '']);",
281
+ " }",
282
+ " return origExecFile.apply(this, arguments);",
283
+ "};",
284
+ "cp.spawn = function(command, args, options) {",
285
+ " if (isBrowserOpen(command, args)) {",
286
+ " return origSpawn.call(this, process.execPath, ['-e', ''], { stdio: 'ignore' });",
287
+ " }",
288
+ " return origSpawn.apply(this, arguments);",
289
+ "};",
290
+ "cp.exec = function(command, options, callback) {",
291
+ " if (typeof command === 'string' && /^(?:start\\b|open\\b|xdg-open\\b|(?:powershell|pwsh)(?:\\.exe)?\\b)/i.test(command.trim()) && hasHttpOrStart(command)) {",
292
+ " const cb = typeof options === 'function' ? options : callback;",
293
+ " if (typeof cb === 'function') queueMicrotask(() => cb(null, '', ''));",
294
+ " return origExecFile.call(this, process.execPath, ['-e', '']);",
295
+ " }",
296
+ " return origExec.apply(this, arguments);",
297
+ "};",
298
+ "syncBuiltinESMExports();",
299
+ ].join("\n"),
300
+ "utf8",
301
+ ).toString("base64");
302
+
303
+ /**
304
+ * 为 Node 22+ 编写的 CLI 登录子进程阻断 `cmd /c start`、`open`、`xdg-open` 与 `rundll32` 打开外部网页,
305
+ * 让授权链接只由发起登录的本地客户端拉起浏览器。
306
+ */
307
+ export function suppressNodeCliBrowserOpen(
308
+ env: Readonly<Record<string, string | undefined>>,
309
+ ): Record<string, string | undefined> {
310
+ const flag = `--import ${NODE_BROWSER_SUPPRESSION_PRELOAD}`;
311
+ const existing = env.NODE_OPTIONS?.trim() ?? "";
312
+ return {
313
+ ...env,
314
+ BROWSER: env.BROWSER ?? NO_BROWSER_SENTINEL,
315
+ NODE_OPTIONS: existing.length > 0 ? `${existing} ${flag}` : flag,
316
+ };
317
+ }
318
+
319
+ /** 脱敏授权码登录错误文本,剥除回显的授权码片段、回调 URL 查询参数值与 `#` 复合令牌。 */
320
+ export function sanitizeAuthorizationCodeError(
321
+ rawMessage: string,
322
+ fallback: string,
323
+ secrets: readonly string[] = [],
324
+ ): string {
325
+ const expanded = new Set<string>();
326
+ for (const secret of secrets) {
327
+ const trimmed = secret.trim();
328
+ if (trimmed.length >= 4) expanded.add(trimmed);
329
+ for (const part of trimmed.split("#")) {
330
+ if (part.trim().length >= 4) expanded.add(part.trim());
331
+ }
332
+ try {
333
+ const parsed = new URL(trimmed);
334
+ for (const [, value] of parsed.searchParams) {
335
+ if (value.trim().length >= 4) expanded.add(value.trim());
336
+ }
337
+ const hash = parsed.hash.replace(/^#/, "").trim();
338
+ if (hash.length >= 4) expanded.add(hash);
339
+ } catch {
340
+ // 非完整 URL 原文忽略。
341
+ }
342
+ }
343
+ let text = rawMessage.replace(ANSI_ESCAPE_SEQUENCES, "").trim();
344
+ for (const token of expanded) {
345
+ text = text.replaceAll(token, "[redacted]");
346
+ }
347
+ text = text
348
+ .replace(/https?:\/\/[^\s"'<>]+/giu, (rawUrl) => {
349
+ try {
350
+ const parsed = new URL(rawUrl);
351
+ return `${parsed.origin}${parsed.pathname}`;
352
+ } catch {
353
+ return "[redacted-url]";
354
+ }
355
+ })
356
+ .replace(/\b(?:code|state|access_token|refresh_token)=[^\s&"'<>]+/giu, "[redacted]")
357
+ .replace(/[A-Za-z0-9._~-]{4,}#[A-Za-z0-9._~-]{4,}/gu, "[redacted]")
358
+ .replace(/\s+/gu, " ")
359
+ .trim();
360
+ return text.length > 0 ? text : fallback;
361
+ }
362
+
363
+ function readCliChallengeOutput<T>(
172
364
  stream: AsyncIterable<Uint8Array>,
173
- parse: (text: string) => DeviceChallenge | undefined,
365
+ parse: (text: string) => T | undefined,
174
366
  ): {
175
367
  readonly drained: Promise<void>;
176
- readonly code: Promise<{ readonly verificationUrl?: string; readonly userCode?: string }>;
368
+ readonly challenge: Promise<T | undefined>;
369
+ readonly tail: () => string;
177
370
  } {
178
371
  let collected = "";
179
- let challenge: DeviceChallenge | undefined;
180
- let onCodeFound: (() => void) | undefined;
181
- const codeFound = new Promise<void>((resolve) => {
182
- onCodeFound = resolve;
372
+ let streamEnded = false;
373
+ let found: T | undefined;
374
+ let onFound: (() => void) | undefined;
375
+ const challengeFound = new Promise<void>((resolve) => {
376
+ onFound = resolve;
183
377
  });
184
378
  let quietTimer: NodeJS.Timeout | undefined;
185
379
  let onQuiet: (() => void) | undefined;
186
380
  const outputWentQuiet = new Promise<void>((resolve) => {
187
381
  onQuiet = resolve;
188
382
  });
383
+ const parseCompleteLines = (): T | undefined => {
384
+ const lastNewline = collected.lastIndexOf("\n");
385
+ return lastNewline >= 0 ? parse(collected.slice(0, lastNewline + 1)) : undefined;
386
+ };
387
+ const recordMatch = (candidate: T | undefined) => {
388
+ if (candidate === undefined || found !== undefined) return;
389
+ found = candidate;
390
+ if (onFound !== undefined) {
391
+ onFound();
392
+ onFound = undefined;
393
+ }
394
+ };
189
395
  const drained = (async () => {
190
396
  const decoder = new TextDecoder();
191
397
  for await (const chunk of stream) {
192
398
  const piece = decoder.decode(chunk, { stream: true });
193
399
  collected = (collected + piece).slice(-16_384);
194
- challenge ??= parse(collected);
195
- if (onCodeFound !== undefined && challenge) {
196
- onCodeFound();
197
- onCodeFound = undefined;
198
- }
199
- // code 给出之后进程还会一直输出到用户批准,不再为它起计时器。
200
- if (onQuiet !== undefined) {
400
+ // 流尚未结束时只解析已闭合的完整行,避免管道或静默窗口在 URL 中间分块时锁死半截前缀。
401
+ recordMatch(parseCompleteLines());
402
+ // 挑战给出之后进程还会一直输出到用户批准,不再为它起计时器。
403
+ if (onQuiet !== undefined && found === undefined) {
201
404
  clearTimeout(quietTimer);
202
- quietTimer = setTimeout(() => onQuiet?.(), OUTPUT_QUIET_MS);
405
+ quietTimer = setTimeout(() => {
406
+ recordMatch(parseCompleteLines());
407
+ onQuiet?.();
408
+ }, OUTPUT_QUIET_MS);
203
409
  }
204
410
  }
411
+ const rest = decoder.decode();
412
+ if (rest.length > 0) {
413
+ collected = (collected + rest).slice(-16_384);
414
+ }
415
+ streamEnded = true;
416
+ recordMatch(parse(collected));
205
417
  })();
206
- const code = (async () => {
418
+ const challenge = (async () => {
207
419
  let silentCap: NodeJS.Timeout | undefined;
208
420
  try {
209
421
  await Promise.race([
210
- codeFound,
422
+ challengeFound,
211
423
  drained,
212
424
  outputWentQuiet,
213
425
  new Promise<void>((resolve) => {
214
426
  silentCap = setTimeout(resolve, SILENT_CAP_MS);
215
427
  }),
216
428
  ]);
217
- return challenge ?? {};
429
+ found ??= streamEnded ? parse(collected) : parseCompleteLines();
430
+ return found;
218
431
  } finally {
219
432
  clearTimeout(silentCap);
220
433
  clearTimeout(quietTimer);
221
434
  onQuiet = undefined;
222
435
  }
223
436
  })();
224
- return { drained, code };
437
+ return { drained, challenge, tail: () => collected };
438
+ }
439
+
440
+ function collectBoundedStream(stream: AsyncIterable<Uint8Array>): {
441
+ readonly drained: Promise<void>;
442
+ readonly tail: () => string;
443
+ } {
444
+ let collected = "";
445
+ const drained = (async () => {
446
+ const decoder = new TextDecoder();
447
+ for await (const chunk of stream) {
448
+ collected = (collected + decoder.decode(chunk, { stream: true })).slice(-16_384);
449
+ }
450
+ })();
451
+ return { drained, tail: () => collected };
225
452
  }
226
453
 
227
454
  type Operation = {
455
+ submitted?: boolean;
456
+ secrets: string[];
228
457
  readonly handle: Awaited<ReturnType<ExecutorHost["process"]["spawn"]>>;
458
+ readonly drained: Promise<unknown>;
459
+ readonly stdoutTail: () => string;
460
+ readonly stderrTail: () => string;
229
461
  readonly close: () => Promise<void>;
230
462
  };
231
463
 
232
- /** 登录记录保留到进程与输出收尾完成;核验、取消与 dispose 共用同一份关闭。 */
233
- export function createCliDeviceSignIn(input: {
464
+ function createCliSignInSession<T>(input: {
465
+ readonly interaction?: "device-code" | "authorization-code" | "browser" | undefined;
234
466
  readonly name: string;
235
467
  readonly host: ExecutorHost;
236
468
  readonly program: string;
237
469
  readonly args: readonly string[];
238
470
  readonly env: Readonly<Record<string, string | undefined>>;
239
471
  readonly stream: "stdout" | "stderr";
240
- readonly parse: (text: string) => DeviceChallenge | undefined;
472
+ readonly parse: (text: string) => T | undefined;
473
+ readonly toStartResult: (
474
+ parsed: T | undefined,
475
+ operation: Operation,
476
+ ) => Omit<Awaited<ReturnType<NonNullable<ExecutorInstance["signIn"]>["start"]>>, "operationId">;
477
+ readonly submitCode?: ((rawCode: string) => string) | undefined;
478
+ readonly formatExitError?:
479
+ | ((exitCode: number | null, stderr: string, stdout: string) => string | undefined)
480
+ | undefined;
241
481
  readonly probe: ExecutorInstance["probe"];
242
482
  readonly isDisposed: () => boolean;
243
483
  }): { signIn: NonNullable<ExecutorInstance["signIn"]>; close: () => Promise<void> } {
244
- const { host } = input;
245
484
  const operations = new Map<string, Operation>();
246
485
  const signIn: NonNullable<ExecutorInstance["signIn"]> = {
486
+ ...(input.interaction === undefined ? {} : { interaction: input.interaction }),
247
487
  start: async (signal) => {
248
488
  if (input.program.length === 0)
249
489
  throw new Error(`${input.name} program path is not configured`);
250
- const env = input.env;
251
- const handle = await host.process.spawn({
490
+ const spawnEnv = {
491
+ ...input.env,
492
+ BROWSER: input.env.BROWSER ?? NO_BROWSER_SENTINEL,
493
+ };
494
+ const handle = await input.host.process.spawn({
252
495
  program: input.program,
253
496
  args: [...input.args],
254
- owner: { bindingId: host.bindingId },
255
- ...(Object.keys(env).length > 0 ? { env } : {}),
497
+ owner: { bindingId: input.host.bindingId },
498
+ env: spawnEnv,
256
499
  ...(signal === undefined ? {} : { signal }),
257
500
  });
258
- const output = readDeviceCodeOutput(handle[input.stream], input.parse);
501
+ const primary = readCliChallengeOutput(handle[input.stream], input.parse);
502
+ const secondary = collectBoundedStream(
503
+ handle[input.stream === "stdout" ? "stderr" : "stdout"],
504
+ );
259
505
  const operationId = NodeCrypto.randomUUID();
260
506
  let closing: Promise<void> | undefined;
507
+ const drained = Promise.allSettled([primary.drained, secondary.drained]);
261
508
  const operation: Operation = {
509
+ submitted: false,
510
+ secrets: [],
262
511
  handle,
512
+ drained,
513
+ stdoutTail: () => (input.stream === "stdout" ? primary.tail() : secondary.tail()),
514
+ stderrTail: () => (input.stream === "stderr" ? primary.tail() : secondary.tail()),
263
515
  close: () =>
264
516
  (closing ??= Promise.resolve()
265
517
  .then(async () => {
266
518
  await handle.kill("SIGTERM").catch(() => undefined);
267
519
  // 宿主的 exited 包含有界排空与进程 Scope 清理。
268
- await Promise.allSettled([handle.exited, output.drained]);
520
+ await Promise.allSettled([handle.exited, drained]);
269
521
  })
270
522
  .finally(() => {
523
+ operation.secrets.length = 0;
271
524
  if (operations.get(operationId) === operation) operations.delete(operationId);
272
525
  })),
273
526
  };
274
527
  operations.set(operationId, operation);
275
528
  try {
276
- const code = await raceAbort(output.code, signal);
529
+ const parsed = await raceAbort(primary.challenge, signal);
277
530
  if (signal?.aborted || input.isDisposed())
278
531
  throw new Error(`${input.name} sign-in cancelled`);
279
- return { operationId, ...code };
532
+ return { operationId, ...input.toStartResult(parsed, operation) };
280
533
  } catch (error) {
281
534
  await operation.close();
282
535
  throw error;
283
536
  }
284
537
  },
538
+ ...(input.submitCode === undefined
539
+ ? {}
540
+ : {
541
+ submit: async (operationId: string, rawCode: string, signal?: AbortSignal) => {
542
+ signal?.throwIfAborted();
543
+ const operation = operations.get(operationId);
544
+ if (operation === undefined) {
545
+ throw new Error(`There is no active ${input.name} sign-in.`);
546
+ }
547
+ if (operation.submitted) {
548
+ throw new Error(
549
+ `The sign-in code was already submitted. Wait for ${input.name} to finish.`,
550
+ );
551
+ }
552
+ const code = input.submitCode!(rawCode);
553
+ if (code.length === 0) {
554
+ throw new Error("Paste the sign-in code from the authorization page.");
555
+ }
556
+ operation.secrets.push(rawCode, code, ...code.split("#"));
557
+ operation.submitted = true;
558
+ await raceAbort(
559
+ operation.handle.writeStdin(new TextEncoder().encode(`${code}\n`)),
560
+ signal,
561
+ );
562
+ },
563
+ }),
285
564
  cancel: async (operationId) => {
286
565
  await operations.get(operationId)?.close();
287
566
  },
@@ -290,7 +569,23 @@ export function createCliDeviceSignIn(input: {
290
569
  try {
291
570
  for (const operation of active) {
292
571
  const code = await raceAbort(operation.handle.exited, signal);
293
- if (code !== 0) throw new Error(`${input.name} sign-in exited with code ${String(code)}`);
572
+ if (input.formatExitError !== undefined || input.interaction === "authorization-code") {
573
+ await raceAbort(operation.drained, signal).catch(() => undefined);
574
+ }
575
+ if (code !== 0) {
576
+ const fallback = `${input.name} sign-in exited with code ${String(code)}`;
577
+ const custom = input.formatExitError?.(
578
+ code,
579
+ operation.stderrTail(),
580
+ operation.stdoutTail(),
581
+ );
582
+ const rawError = custom ?? fallback;
583
+ throw new Error(
584
+ input.interaction === "authorization-code"
585
+ ? sanitizeAuthorizationCodeError(rawError, fallback, operation.secrets)
586
+ : rawError,
587
+ );
588
+ }
294
589
  }
295
590
  return await input.probe(signal);
296
591
  } finally {
@@ -305,3 +600,88 @@ export function createCliDeviceSignIn(input: {
305
600
  },
306
601
  };
307
602
  }
603
+
604
+ /** 登录记录保留到进程与输出收尾完成;核验、取消与 dispose 共用同一份关闭。 */
605
+ export function createCliDeviceSignIn(input: {
606
+ readonly name: string;
607
+ readonly host: ExecutorHost;
608
+ readonly program: string;
609
+ readonly args: readonly string[];
610
+ readonly env: Readonly<Record<string, string | undefined>>;
611
+ readonly stream: "stdout" | "stderr";
612
+ readonly parse: (text: string) => DeviceChallenge | undefined;
613
+ readonly probe: ExecutorInstance["probe"];
614
+ readonly isDisposed: () => boolean;
615
+ }): { signIn: NonNullable<ExecutorInstance["signIn"]>; close: () => Promise<void> } {
616
+ return createCliSignInSession({
617
+ ...input,
618
+ interaction: "device-code",
619
+ toStartResult: (challenge) => challenge ?? {},
620
+ });
621
+ }
622
+
623
+ function requireCliSignInUrl(
624
+ name: string,
625
+ verificationUrl: string | undefined,
626
+ stderrTail: () => string,
627
+ ): { readonly verificationUrl: string } {
628
+ const trimmed = verificationUrl?.trim();
629
+ if (!trimmed) {
630
+ const detail = stderrTail().trim();
631
+ throw new Error(detail.length > 0 ? detail : `${name} did not output a sign-in link.`);
632
+ }
633
+ return { verificationUrl: trimmed };
634
+ }
635
+
636
+ type CliUrlSignInInput = {
637
+ readonly name: string;
638
+ readonly host: ExecutorHost;
639
+ readonly program: string;
640
+ readonly args: readonly string[];
641
+ readonly env: Readonly<Record<string, string | undefined>>;
642
+ readonly stream?: "stdout" | "stderr" | undefined;
643
+ readonly parseUrl: (text: string) => string | undefined;
644
+ readonly probe: ExecutorInstance["probe"];
645
+ readonly isDisposed: () => boolean;
646
+ };
647
+
648
+ /** 无回填码的网页授权登录:启动 CLI 读取授权链接,等用户在本地浏览器完成授权并由 CLI 轮询退出后重探。 */
649
+ export function createCliBrowserSignIn(input: CliUrlSignInInput): {
650
+ signIn: NonNullable<ExecutorInstance["signIn"]>;
651
+ close: () => Promise<void>;
652
+ } {
653
+ const { stream = "stdout", parseUrl, ...rest } = input;
654
+ return createCliSignInSession({
655
+ ...rest,
656
+ interaction: "browser",
657
+ stream,
658
+ parse: parseUrl,
659
+ toStartResult: (url, operation) =>
660
+ requireCliSignInUrl(input.name, url, () => operation.stderrTail()),
661
+ });
662
+ }
663
+
664
+ /**
665
+ * 网页授权回填登录:启动 CLI 读取授权链接,把用户粘回的授权码或回调地址写进 stdin,再等进程落定后重探。
666
+ * 输入校验失败只抛错而不关进程,用户可以修正后再次提交。
667
+ */
668
+ export function createCliAuthorizationCodeSignIn(
669
+ input: CliUrlSignInInput & {
670
+ readonly normalizeCode?: ((code: string) => string) | undefined;
671
+ readonly formatExitError?:
672
+ | ((exitCode: number | null, stderr: string, stdout: string) => string | undefined)
673
+ | undefined;
674
+ },
675
+ ): { signIn: NonNullable<ExecutorInstance["signIn"]>; close: () => Promise<void> } {
676
+ const { stream = "stdout", parseUrl, normalizeCode, formatExitError, ...rest } = input;
677
+ return createCliSignInSession({
678
+ ...rest,
679
+ interaction: "authorization-code",
680
+ stream,
681
+ parse: parseUrl,
682
+ toStartResult: (url, operation) =>
683
+ requireCliSignInUrl(input.name, url, () => operation.stderrTail()),
684
+ submitCode: (rawCode) => (normalizeCode ? normalizeCode(rawCode) : rawCode.trim()),
685
+ formatExitError,
686
+ });
687
+ }
package/dist/source/ui.ts CHANGED
@@ -493,7 +493,12 @@ export interface PluginUiBridge<Ui = unknown, Layout = unknown, React = unknown>
493
493
  ): string;
494
494
  useProviderName?(environmentId: string | null, instanceId: string, fallbackName?: string): string;
495
495
  useThreadName?(threadRef: PluginUiThreadNameProps["threadRef"], fallbackName?: string): string;
496
- usePluginName?(environmentId: string | null, pluginId: string, fallbackName?: string): string;
496
+ usePluginName?(
497
+ environmentId: string | null,
498
+ pluginId: string,
499
+ fallbackName?: string,
500
+ entryId?: string,
501
+ ): string;
497
502
  /** 工作项状态在界面上叫什么:默认状态按界面语言,改过名的与自定义的照原名。是 hook;旧宿主缺席时显示 `name`。 */
498
503
  useWorkStateName?(): (state: {
499
504
  readonly name: string;
@@ -9,7 +9,7 @@
9
9
  *
10
10
  * @module @ycodium-ai/plugin-api/version
11
11
  */
12
- export const PLUGIN_API_VERSION = 194;
12
+ export const PLUGIN_API_VERSION = 197;
13
13
  export const PLUGIN_API_MIN_VERSION = 193;
14
14
  /** 插件可以声明的版本:窗口内的每一个。 */
15
- export type PluginApiVersion = 193 | 194;
15
+ export type PluginApiVersion = 193 | 194 | 195 | 196 | 197;
package/dist/ui.d.ts CHANGED
@@ -431,7 +431,7 @@ export interface PluginUiBridge<Ui = unknown, Layout = unknown, React = unknown>
431
431
  useProjectName?(projectRef: PluginUiProjectNameProps["projectRef"], fallbackName?: string): string;
432
432
  useProviderName?(environmentId: string | null, instanceId: string, fallbackName?: string): string;
433
433
  useThreadName?(threadRef: PluginUiThreadNameProps["threadRef"], fallbackName?: string): string;
434
- usePluginName?(environmentId: string | null, pluginId: string, fallbackName?: string): string;
434
+ usePluginName?(environmentId: string | null, pluginId: string, fallbackName?: string, entryId?: string): string;
435
435
  /** 工作项状态在界面上叫什么:默认状态按界面语言,改过名的与自定义的照原名。是 hook;旧宿主缺席时显示 `name`。 */
436
436
  useWorkStateName?(): (state: {
437
437
  readonly name: string;