docs(cli-account): document the kit's contracts
Document the executor's deadlines and output limits, the runtime's one-operation, phase-gated cancellation, trusted-link, and classified-failure contracts, the shared config fields, and the client mirror and components.
This commit is contained in:
1 parent
64d8d52106
commit
57c8447e98
9 files changed
+228
No files matched your search
@@ -1,3 +1,4 @@
|
||||
/** Plugins page components shared by CLI plugins: they render a plugin's display phase with the copy the plugin translates. */
|
||||
import { useEffect, type ReactNode } from 'react'
|
||||
import { Button, IconWarningOutlineRegular, Modal, StateDot, Tag, Toast, type StateDotState, type TagTone } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { PropsRuntime, Translate } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
@@ -6,8 +7,10 @@ import type { CliCommandFailure } from '@deepseek-ai/dsh-cli-account/types'
|
||||
import type { CliAccountNotice } from './connection.ts'
|
||||
import css from './CliAccount.module.css'
|
||||
|
||||
/** What the page shows about a plugin's account; each plugin maps its own account states onto these phases. */
|
||||
export type CliAccountPhase = 'checking' | 'connecting' | 'connected' | 'disconnected' | 'unavailable' | 'stopped'
|
||||
|
||||
/** Dictionary keys every CLI plugin translates for the shared components. */
|
||||
export type CliAccountKey =
|
||||
| 'section.title' | 'hint' | 'close' | 'action.cancel' | 'action.connect'
|
||||
| 'activation.title' | 'activation.body' | 'activation.later'
|
||||
@@ -23,34 +26,46 @@ const BADGE_TONE: Record<Exclude<CliAccountPhase, 'checking'>, TagTone> = {
|
||||
connecting: 'info', connected: 'success', disconnected: 'outline', unavailable: 'warning', stopped: 'warning',
|
||||
}
|
||||
|
||||
/** One button in the section; the section disables it while an action is pending or the Host stream is down. */
|
||||
export interface CliAccountAction {
|
||||
readonly label: string
|
||||
readonly onClick: () => void
|
||||
/** Defaults to an outline button. */
|
||||
readonly variant?: 'primary' | 'ghost'
|
||||
}
|
||||
|
||||
/** One extra row under the status line, such as the linked app, with an optional button. */
|
||||
export interface CliAccountNote {
|
||||
readonly text: string
|
||||
readonly action?: CliAccountAction
|
||||
}
|
||||
|
||||
/** A failed operation as the section reports it. */
|
||||
export interface CliAccountFailure {
|
||||
/** The plugin's recovery guidance. */
|
||||
readonly text: string
|
||||
/** The Host's classified command, shown as a diagnostic after the guidance. */
|
||||
readonly command?: CliCommandFailure | undefined
|
||||
/** The plugin's allowlisted classification fields, appended in order; undefined entries are skipped. */
|
||||
readonly details?: readonly (string | undefined)[]
|
||||
}
|
||||
|
||||
/** What the section shows about one plugin's account. */
|
||||
export interface CliAccountSectionProps {
|
||||
readonly t: Translate<CliAccountKey>
|
||||
readonly packageName: string
|
||||
readonly phase: CliAccountPhase
|
||||
/** The status label; defaults to the `status.*` copy for the phase, with `connecting` labelled as checking. */
|
||||
readonly status?: string | undefined
|
||||
/** Whether an action this page started has not answered. */
|
||||
readonly busy: boolean
|
||||
/** Whether the Host stream is delivering; buttons stay enabled while stopped so retry can reopen it. */
|
||||
readonly linked: boolean
|
||||
readonly actions: readonly CliAccountAction[]
|
||||
readonly detail?: string | undefined
|
||||
readonly notes?: readonly CliAccountNote[]
|
||||
readonly failure?: CliAccountFailure | undefined
|
||||
/** Extra content rendered last, such as confirmation dialogs. */
|
||||
readonly children?: ReactNode
|
||||
}
|
||||
|
||||
@@ -65,6 +80,11 @@ function describe(t: Translate<CliAccountKey>, failure: CliAccountFailure): stri
|
||||
return t('failure.details', { details })
|
||||
}
|
||||
|
||||
/**
|
||||
* The account section on a plugin's bundle page.
|
||||
* @param props - the phase, status, buttons, rows, and failure, with the plugin's translator.
|
||||
* @returns the title, status line, detail, rows, failure, hint, and children.
|
||||
*/
|
||||
export function CliAccountSection(props: CliAccountSectionProps): ReactNode {
|
||||
const { t, packageName, phase, status, busy, linked, actions, detail, notes = [], failure, children } = props
|
||||
// Reopening a stopped stream is the one action that does not need the Host stream.
|
||||
@@ -94,6 +114,7 @@ export function CliAccountSection(props: CliAccountSectionProps): ReactNode {
|
||||
)
|
||||
}
|
||||
|
||||
/** The tag's subject and phase, with the plugin's translator. */
|
||||
export interface CliAccountBadgeProps {
|
||||
readonly t: Translate<CliAccountKey>
|
||||
readonly subject: PropsRuntime<'plugins.detail.badge'>['subject']
|
||||
@@ -101,11 +122,17 @@ export interface CliAccountBadgeProps {
|
||||
readonly phase: CliAccountPhase
|
||||
}
|
||||
|
||||
/**
|
||||
* The account tag beside a plugin bundle's title.
|
||||
* @param props - the open detail page's subject, the plugin's package, its phase, and its translator.
|
||||
* @returns the tag on the enabled bundle's page once the phase settles, or null.
|
||||
*/
|
||||
export function CliAccountBadge({ t, subject, packageName, phase }: CliAccountBadgeProps): ReactNode {
|
||||
if (subject.kind === 'item' || subject.pkg.name !== packageName || !subject.pkg.enabled || phase === 'checking') return null
|
||||
return <Tag tone={BADGE_TONE[phase]}>{t(`badge.${phase}`)}</Tag>
|
||||
}
|
||||
|
||||
/** The prompt's phase and callbacks, with the plugin's translator. */
|
||||
export interface CliAccountActivationProps {
|
||||
readonly t: Translate<CliAccountKey>
|
||||
readonly phase: CliAccountPhase
|
||||
@@ -113,6 +140,11 @@ export interface CliAccountActivationProps {
|
||||
readonly onConnect: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Guidance after the user switches a plugin bundle on while its account is not connected.
|
||||
* @param props - the phase, the dismiss and connect callbacks, and the plugin's translator.
|
||||
* @returns a prompt shown while disconnected; it dismisses itself once the phase settles elsewhere.
|
||||
*/
|
||||
export function CliAccountActivation({ t, phase, onDismiss, onConnect }: CliAccountActivationProps): ReactNode {
|
||||
const needed = phase === 'disconnected'
|
||||
useEffect(() => {
|
||||
@@ -129,6 +161,7 @@ export function CliAccountActivation({ t, phase, onDismiss, onConnect }: CliAcco
|
||||
)
|
||||
}
|
||||
|
||||
/** A confirmation's copy and callbacks, with the plugin's translator for the shared buttons. */
|
||||
export interface CliAccountConfirmProps {
|
||||
readonly t: Translate<CliAccountKey>
|
||||
readonly open: boolean
|
||||
@@ -139,6 +172,11 @@ export interface CliAccountConfirmProps {
|
||||
readonly onConfirm: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Confirm an action that changes the account outside DSH, such as signing out of a CLI the terminal shares.
|
||||
* @param props - whether it is open, its copy, and the close and confirm callbacks.
|
||||
* @returns a dialog that closes before it confirms.
|
||||
*/
|
||||
export function CliAccountConfirm({ t, open, title, body, confirm, onClose, onConfirm }: CliAccountConfirmProps): ReactNode {
|
||||
return (
|
||||
<Modal open={open} title={title} closeLabel={t('close')} onClose={onClose}
|
||||
@@ -151,12 +189,18 @@ export function CliAccountConfirm({ t, open, title, body, confirm, onClose, onCo
|
||||
)
|
||||
}
|
||||
|
||||
/** The latest notice, with the plugin's translator for `notice.*` copy. */
|
||||
export interface CliAccountToastProps<Notice extends string> {
|
||||
readonly t: Translate<`notice.${NoInfer<CliAccountNotice<Notice>['kind']>}`>
|
||||
readonly notice: CliAccountNotice<Notice> | undefined
|
||||
readonly onDone: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Account outcomes reported outside the Plugins panel's lifetime.
|
||||
* @param props - the latest notice, its dismissal, and the plugin's translator.
|
||||
* @returns the toast for the notice, or null.
|
||||
*/
|
||||
export function CliAccountToast<Notice extends string>({ t, notice, onDone }: CliAccountToastProps<Notice>): ReactNode {
|
||||
if (notice === undefined) return null
|
||||
const failed = notice.kind === 'action-failed'
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
/** Browser mirror of one CLI plugin's Host account view and the Plugins page's account actions. */
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import type { RemoteStream } from '@deepseek-ai/dsh-api-gateway/client'
|
||||
import type {} from '@deepseek-ai/dsh-api-remotes/client'
|
||||
@@ -8,23 +9,34 @@ import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol'
|
||||
type AnyView = CliAccountView<unknown, string, string>
|
||||
type KindOf<View extends AnyView> = NonNullable<View['result']>['kind']
|
||||
|
||||
/** A transient outcome the page reports outside its own lifetime; `seq` distinguishes repeats. */
|
||||
export interface CliAccountNotice<Notice extends string> {
|
||||
readonly seq: number
|
||||
readonly kind: Notice | 'action-failed'
|
||||
}
|
||||
|
||||
/** The page's whole view: the Host's account view plus this browser's pending action and notice. */
|
||||
export interface CliAccountSnapshot<View extends AnyView, Notice extends string> {
|
||||
/** The Host's view; undefined until the stream reports one. */
|
||||
readonly view: View | undefined
|
||||
/** Whether the Host stream is delivering. */
|
||||
readonly linked: boolean
|
||||
/** Whether the Host stream failed for good, as when the plugin's Host component is not running; `retry` reopens it. */
|
||||
readonly stopped: boolean
|
||||
/** Whether an action this page started has not answered. */
|
||||
readonly busy: boolean
|
||||
readonly notice: CliAccountNotice<Notice> | undefined
|
||||
}
|
||||
|
||||
/** The plugin's Remote operations the mirror uses and the notices its successes report. */
|
||||
export interface CliAccountConnectionOptions<View extends AnyView, Notice extends string> {
|
||||
/** Diagnostic name of the Host stream. */
|
||||
readonly name: string
|
||||
/** Open one generation of the plugin's `follow` stream. */
|
||||
readonly follow: (signal: AbortSignal) => AsyncIterable<View>
|
||||
/** Cancel one operation through the plugin's Remote. */
|
||||
readonly cancel: (id: CliOperationId) => Promise<RemoteResult<void>>
|
||||
/** The notice each operation kind reports when an operation this browser started succeeds; unlisted kinds report none. */
|
||||
readonly notices: Readonly<Partial<Record<KindOf<View>, Notice>>>
|
||||
}
|
||||
|
||||
@@ -38,11 +50,14 @@ async function settle<T>(call: Promise<RemoteResult<T>>): Promise<T> {
|
||||
return result.value
|
||||
}
|
||||
|
||||
/** One Host subscription per plugin page, shared by every surface of that plugin on the Plugins page. */
|
||||
export class CliAccountConnection<View extends AnyView, Notice extends string> {
|
||||
/** The page's whole view, published after each stream item or page action settles. */
|
||||
readonly state: SnapshotStore<CliAccountSnapshot<View, Notice>> = createSnapshotStore<CliAccountSnapshot<View, Notice>>({
|
||||
view: undefined, linked: false, stopped: false, busy: false, notice: undefined,
|
||||
})
|
||||
|
||||
/** The operation this browser started; only its links open a window here. */
|
||||
private started: CliOperationId | undefined
|
||||
private readonly opened = new Set<string>()
|
||||
private seq = 0
|
||||
@@ -50,6 +65,7 @@ export class CliAccountConnection<View extends AnyView, Notice extends string> {
|
||||
private stream!: RemoteStream<View>
|
||||
private observing!: Promise<void>
|
||||
|
||||
/** The page actions every plugin's face exposes unchanged, bound so slot handlers can call them directly. */
|
||||
readonly actions = {
|
||||
cancel: (): void => { this.cancel() },
|
||||
openAuthorization: (): void => { this.openAuthorization() },
|
||||
@@ -57,10 +73,19 @@ export class CliAccountConnection<View extends AnyView, Notice extends string> {
|
||||
dismissNotice: (): void => { this.dismissNotice() },
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ctx - the plugin's browser context, carrying the Remote client.
|
||||
* @param options - the plugin's Remote operations and success notices.
|
||||
*/
|
||||
constructor(private readonly ctx: Context, private readonly options: CliAccountConnectionOptions<View, Notice>) {
|
||||
this.subscribe()
|
||||
}
|
||||
|
||||
/**
|
||||
* Start an operation through the plugin's Remote; a click while another action is pending is ignored,
|
||||
* and a rejected start reports the `action-failed` notice.
|
||||
* @param call - the plugin's Remote start method.
|
||||
*/
|
||||
start(call: () => Promise<RemoteResult<CliOperationId>>): void {
|
||||
void this.run(async () => {
|
||||
this.started = await settle(call())
|
||||
@@ -69,24 +94,32 @@ export class CliAccountConnection<View extends AnyView, Notice extends string> {
|
||||
})
|
||||
}
|
||||
|
||||
/** Cancel the current operation when the Host marks it cancellable. */
|
||||
cancel(): void {
|
||||
const operation = this.state.getSnapshot().view?.operation
|
||||
if (operation === undefined || !operation.cancellable) return
|
||||
void this.run(async () => { await settle(this.options.cancel(operation.id)) })
|
||||
}
|
||||
|
||||
/** Open the current operation's authorization link again, over HTTPS only. */
|
||||
openAuthorization(): void {
|
||||
openAuthorizationPage(this.state.getSnapshot().view?.operation?.authorizationUrl)
|
||||
}
|
||||
|
||||
/** Reopen the Host stream after it stopped; ignored while it runs or after disposal. */
|
||||
retry(): void {
|
||||
void this.reopen()
|
||||
}
|
||||
|
||||
/** Clear the current notice. */
|
||||
dismissNotice(): void {
|
||||
this.patch({ notice: undefined })
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop observing the Host and report nothing more; Host-owned operations keep running.
|
||||
* @returns after the stream closes.
|
||||
*/
|
||||
async dispose(): Promise<void> {
|
||||
this.disposed = true
|
||||
await this.stream.dispose()
|
||||
@@ -110,6 +143,7 @@ export class CliAccountConnection<View extends AnyView, Notice extends string> {
|
||||
item.accept()
|
||||
}
|
||||
} catch {
|
||||
// A terminal failure, such as a Host without the plugin's service, ends the stream; a disposed page shows nothing.
|
||||
if (!this.disposed) this.patch({ linked: false, stopped: true })
|
||||
}
|
||||
}
|
||||
@@ -122,6 +156,7 @@ export class CliAccountConnection<View extends AnyView, Notice extends string> {
|
||||
this.subscribe()
|
||||
}
|
||||
|
||||
/** Open each new link of this browser's operation once, and report how the operation ended. */
|
||||
private follow(view: View): void {
|
||||
const operation = view.operation
|
||||
if (operation !== undefined && operation.id === this.started && operation.authorizationUrl !== undefined
|
||||
@@ -142,6 +177,7 @@ export class CliAccountConnection<View extends AnyView, Notice extends string> {
|
||||
try {
|
||||
await operation()
|
||||
} catch {
|
||||
// The Host keeps the diagnostic; the page reports one retryable outcome.
|
||||
this.notify('action-failed')
|
||||
} finally {
|
||||
this.patch({ busy: false })
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
/**
|
||||
* Shared Plugins page pieces of CLI app plugins, browser half. The web app mounts this row once; plugins request it
|
||||
* through `dsh.client.external` and import its connection mirror and components from the module table.
|
||||
*/
|
||||
export {
|
||||
CliAccountActivation, CliAccountBadge, CliAccountConfirm, CliAccountSection, CliAccountToast,
|
||||
type CliAccountAction, type CliAccountActivationProps, type CliAccountBadgeProps, type CliAccountConfirmProps, type CliAccountFailure,
|
||||
@@ -5,4 +9,5 @@ export {
|
||||
} from './components.tsx'
|
||||
export { CliAccountConnection, type CliAccountConnectionOptions, type CliAccountNotice, type CliAccountSnapshot } from './connection.ts'
|
||||
|
||||
/** The row has no browser behavior of its own; plugins use its exports. */
|
||||
export function apply(): void {}
|
||||
@@ -1 +1,4 @@
|
||||
/** Host marker for the shared CLI plugin page pieces; the browser half is the client export. */
|
||||
|
||||
/** The row has no Host behavior. */
|
||||
export function apply(): void {}
|
||||
@@ -1,11 +1,17 @@
|
||||
/** Config fields that CLI plugins share. */
|
||||
|
||||
import z from '@deepseek-ai/schemastery'
|
||||
import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout'
|
||||
|
||||
/** Where a plugin's CLI is and how long commands that do not wait for the user may run. */
|
||||
export interface CliAccountConfig {
|
||||
/** Absolute directory holding the CLI executable; the plugin defines the default. */
|
||||
binDir?: string
|
||||
/** Deadline in milliseconds for a command that does not wait for the user, including executable lookup. */
|
||||
commandTimeoutMs: number
|
||||
}
|
||||
|
||||
/** Schema for {@link CliAccountConfig}; a plugin with no other fields uses it as its `Config`. */
|
||||
export const CliAccountConfig: z<CliAccountConfig> = z.object({
|
||||
binDir: z.string().min(1),
|
||||
commandTimeoutMs: z.number().min(1).max(MAX_TIMER_DELAY_MS).default(30_000),
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
/** Bounded execution of one CLI program on the private Shell PATH, with subprocess lifetime ownership. */
|
||||
|
||||
import { homedir } from 'node:os'
|
||||
import type { Readable } from 'node:stream'
|
||||
import type { ShellEnvRegistry } from '@deepseek-ai/dsh-shell-env'
|
||||
@@ -10,24 +12,34 @@ const AUTHORIZATION_TIMEOUT_MS = 600_000
|
||||
const TERMINATE_GRACE_MS = 2_000
|
||||
const TIMEOUT_CODE = 'CLI_ACCOUNT_TIMEOUT'
|
||||
|
||||
/** The program a plugin runs and its deadline for commands that do not wait for the user. */
|
||||
export interface CliCommandExecutorOptions {
|
||||
/** Executable name looked up on the private Shell PATH. */
|
||||
readonly program: string
|
||||
/** Deadline in milliseconds, including executable lookup. */
|
||||
readonly commandTimeoutMs: number
|
||||
}
|
||||
|
||||
/** One command that ran to exit; a nonzero exit is the caller's to interpret. */
|
||||
export interface CliCommandResult {
|
||||
readonly exitCode: number | null
|
||||
/** At most 1 MiB of stdout. */
|
||||
readonly stdout: string
|
||||
/** The last 4 KiB of stderr. */
|
||||
readonly stderr: string
|
||||
}
|
||||
|
||||
/** How long one command may run and who observes its output. */
|
||||
export interface CliRunOptions {
|
||||
/** Whether the command waits for the user in a browser; it then gets a fixed 10-minute deadline instead of the command deadline. */
|
||||
readonly awaitsUser?: boolean
|
||||
/** Receives each complete output line, without its line terminator, as the command writes it. */
|
||||
readonly onLine?: (stream: 'stdout' | 'stderr', line: string) => void
|
||||
}
|
||||
|
||||
interface StreamText { text: string; overflowed: boolean }
|
||||
|
||||
/** Drain one pipe, report complete lines, and keep the head up to `maxBytes` or, for a tail, the last `maxBytes`. */
|
||||
async function readStream(
|
||||
stream: Readable | undefined, name: 'stdout' | 'stderr', maxBytes: number, keep: 'head' | 'tail',
|
||||
onLine: CliRunOptions['onLine'],
|
||||
@@ -53,6 +65,7 @@ async function readStream(
|
||||
return result
|
||||
}
|
||||
|
||||
/** Runs one plugin's CLI program and owns each command until its process exits. */
|
||||
export class CliCommandExecutor {
|
||||
private readonly lifetime = new AbortController()
|
||||
private readonly running = new Set<Promise<CliCommandResult>>()
|
||||
@@ -63,6 +76,15 @@ export class CliCommandExecutor {
|
||||
private readonly options: CliCommandExecutorOptions,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Run one command to process exit and return its output whatever the exit code.
|
||||
* @param args - native arguments without the executable.
|
||||
* @param signal - caller cancellation; an abort rejects with its reason after the process exits.
|
||||
* @param options - the deadline choice and an observer for output lines.
|
||||
* @returns the exit code, the stdout head, and the stderr tail.
|
||||
* @throws after disposal; otherwise, with a message naming the command, when the deadline elapses,
|
||||
* the process ends by a signal, or stdout exceeds 1 MiB.
|
||||
*/
|
||||
async run(args: readonly string[], signal: AbortSignal, options: CliRunOptions = {}): Promise<CliCommandResult> {
|
||||
this.lifetime.signal.throwIfAborted()
|
||||
const task = this.execute(args, signal, options)
|
||||
@@ -74,11 +96,20 @@ export class CliCommandExecutor {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Abort owned commands, wait for their processes to exit, and refuse later commands.
|
||||
* @returns settles once every owned command has settled.
|
||||
*/
|
||||
async dispose(): Promise<void> {
|
||||
this.lifetime.abort(new Error(`${this.options.program}: plugin disposed`))
|
||||
await Promise.allSettled([...this.running])
|
||||
}
|
||||
|
||||
/**
|
||||
* Name a command for diagnostics.
|
||||
* @param args - native arguments without the executable.
|
||||
* @returns the program and its arguments joined by spaces.
|
||||
*/
|
||||
commandLine(args: readonly string[]): string {
|
||||
return [this.options.program, ...args].join(' ')
|
||||
}
|
||||
|
||||
@@ -1,3 +1,9 @@
|
||||
/**
|
||||
* Shared Host mechanism of CLI app plugins: run a third-party CLI that owns the user's account on the private Shell PATH,
|
||||
* and run one account operation at a time for the Plugins page. Each plugin keeps its own commands, parsing, and states.
|
||||
* @module @deepseek-ai/dsh-cli-account
|
||||
*/
|
||||
|
||||
export { CliAccountConfig } from './config.ts'
|
||||
export { CliCommandExecutor, type CliCommandExecutorOptions, type CliCommandResult, type CliRunOptions } from './executor.ts'
|
||||
export { CliAccountRuntime, exitFailure, type CliAccountRuntimeOptions, type CliOperationControl } from './runtime.ts'
|
||||
|
||||
@@ -1,26 +1,64 @@
|
||||
/** One CLI plugin's account operations: one at a time, Host-owned, observable by any number of Remote subscribers. */
|
||||
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import { brandString } from '@deepseek-ai/dsh-brand'
|
||||
import type { CliCommandExecutor, CliCommandResult, CliRunOptions } from './executor.ts'
|
||||
import type { CliAccountView, CliCommandFailure, CliOperation, CliOperationId, CliOperationResult } from './types.ts'
|
||||
|
||||
/** What a plugin's operation may do while it runs. */
|
||||
export interface CliOperationControl<Phase extends string, Command extends string> {
|
||||
/**
|
||||
* Enter a phase and withdraw the current link.
|
||||
* @param phase - the plugin's phase, or `checking` for a check that follows another step.
|
||||
* @throws the cancellation reason after the operation was cancelled.
|
||||
*/
|
||||
stage(phase: Phase | 'checking'): void
|
||||
/**
|
||||
* Offer an authorization link to the page; an untrusted, malformed, or late link is ignored.
|
||||
* @param url - an HTTPS URL on one of the plugin's authorization hosts or their subdomains, without credentials.
|
||||
*/
|
||||
offer(url: string): void
|
||||
/**
|
||||
* Run one command and record its classification as the operation's failure if the operation then fails.
|
||||
* @param command - the plugin's identifier for the command.
|
||||
* @param args - native arguments without the executable.
|
||||
* @param signal - the operation's signal.
|
||||
* @param options - the deadline choice and an output-line observer.
|
||||
* @returns the command's exit code and output, whatever the exit code.
|
||||
* @throws what {@link CliCommandExecutor.run} throws.
|
||||
*/
|
||||
run(command: Command, args: readonly string[], signal: AbortSignal, options?: CliRunOptions): Promise<CliCommandResult>
|
||||
}
|
||||
|
||||
/** A plugin's account identity, executor, and rules. */
|
||||
export interface CliAccountRuntimeOptions<Account, Kind extends string, Phase extends string, Failure extends CliCommandFailure> {
|
||||
/** Prefix for errors and log records, such as `wecom`. */
|
||||
readonly name: string
|
||||
/** The executor the runtime runs commands with and disposes with itself. */
|
||||
readonly cli: CliCommandExecutor
|
||||
readonly logger: Context['logger']
|
||||
/** The account before the first check. */
|
||||
readonly account: Account
|
||||
/** The operation each new subscriber starts when none runs. */
|
||||
readonly check: Kind
|
||||
/** The plugin phases in which `cancel` stops an operation; the runtime's own phases are never cancellable. */
|
||||
readonly cancellable: readonly Phase[]
|
||||
/** Hosts whose HTTPS links, and their subdomains' links, may reach the page. */
|
||||
readonly authorizationHosts: readonly string[]
|
||||
/**
|
||||
* Keep only safe, allowlisted facts from a command result; it never sees exception messages.
|
||||
* Before a command exits it receives a result with a null exit code and empty output.
|
||||
*/
|
||||
readonly classify: (command: Failure['command'], result: CliCommandResult) => Failure
|
||||
}
|
||||
|
||||
/**
|
||||
* Classify a command by its exit code alone, for CLIs whose error output has no safe structure.
|
||||
* @param command - the plugin's identifier for the command.
|
||||
* @param result - the command's observed exit code and output.
|
||||
* @returns the command identifier and exit code.
|
||||
*/
|
||||
export function exitFailure<Command extends string>(command: Command, result: CliCommandResult): CliCommandFailure<Command> {
|
||||
return { command, exitCode: result.exitCode }
|
||||
}
|
||||
@@ -45,6 +83,10 @@ class Operation<Kind extends string, Phase extends string, Failure extends CliCo
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs at most one account operation at a time; subscribers observe it without owning it. A failed operation logs and
|
||||
* returns only its last command's classification, because exceptions and native output may contain credentials.
|
||||
*/
|
||||
export abstract class CliAccountRuntime<
|
||||
Account, Kind extends string, Phase extends string, Failure extends CliCommandFailure = CliCommandFailure,
|
||||
> {
|
||||
@@ -55,18 +97,34 @@ export abstract class CliAccountRuntime<
|
||||
private readonly listeners = new Set<() => void>()
|
||||
private readonly lifetime = new AbortController()
|
||||
|
||||
/** @param options - the plugin's account identity, executor, and rules. */
|
||||
constructor(private readonly options: CliAccountRuntimeOptions<Account, Kind, Phase, Failure>) {
|
||||
this.account = options.account
|
||||
this.cancellable = new Set(options.cancellable)
|
||||
}
|
||||
|
||||
/**
|
||||
* Carry out one operation. Throwing fails it, unless the operation was cancelled.
|
||||
* @param kind - the requested operation.
|
||||
* @param control - phase changes, link offers, and classified command runs for this operation.
|
||||
* @param signal - aborts on cancellation or disposal.
|
||||
* @returns after the operation finishes.
|
||||
*/
|
||||
protected abstract perform(kind: Kind, control: CliOperationControl<Phase, Failure['command']>, signal: AbortSignal): Promise<void>
|
||||
|
||||
/**
|
||||
* Replace the account the view reports and notify subscribers.
|
||||
* @param account - the account the latest check observed.
|
||||
*/
|
||||
protected publish(account: Account): void {
|
||||
this.account = account
|
||||
this.changed()
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the account, the active operation, and the last result.
|
||||
* @returns a view without credentials.
|
||||
*/
|
||||
snapshot(): CliAccountView<Account, Kind, Phase, Failure> {
|
||||
return {
|
||||
account: this.account,
|
||||
@@ -75,6 +133,12 @@ export abstract class CliAccountRuntime<
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Start one operation.
|
||||
* @param kind - the requested operation.
|
||||
* @returns the operation identity.
|
||||
* @throws while another operation runs, or after disposal.
|
||||
*/
|
||||
start(kind: Kind): CliOperationId {
|
||||
this.lifetime.signal.throwIfAborted()
|
||||
if (this.active !== undefined) throw new Error(`${this.options.name}: another account operation is in progress`)
|
||||
@@ -86,10 +150,16 @@ export abstract class CliAccountRuntime<
|
||||
return operation.id
|
||||
}
|
||||
|
||||
/** Start a check unless an operation already runs or the runtime is disposed. */
|
||||
refresh(): void {
|
||||
if (this.active === undefined && !this.lifetime.signal.aborted) this.start(this.options.check)
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancel the named operation if its current phase is cancellable, and wait for it to settle.
|
||||
* @param id - the operation to cancel; a finished operation or a phase that is not cancellable is ignored.
|
||||
* @returns after the operation settles, or at once when nothing is cancelled.
|
||||
*/
|
||||
async cancel(id: CliOperationId): Promise<void> {
|
||||
const operation = this.active
|
||||
if (operation?.id !== id || !operation.canCancel) return
|
||||
@@ -97,6 +167,11 @@ export abstract class CliAccountRuntime<
|
||||
await operation.done
|
||||
}
|
||||
|
||||
/**
|
||||
* Follow the account and its operations; each new subscriber starts a check when no operation runs.
|
||||
* @param signal - the subscriber's lifetime; disposal also ends the stream.
|
||||
* @returns the current view, then each changed view, coalescing changes that arrive before the next read.
|
||||
*/
|
||||
async *follow(signal: AbortSignal): AsyncIterable<CliAccountView<Account, Kind, Phase, Failure>> {
|
||||
this.refresh()
|
||||
const combined = AbortSignal.any([signal, this.lifetime.signal])
|
||||
@@ -119,6 +194,10 @@ export abstract class CliAccountRuntime<
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuse new work, cancel the active operation, wait for it, and dispose the executor.
|
||||
* @returns after account work and owned processes stop.
|
||||
*/
|
||||
async dispose(): Promise<void> {
|
||||
this.lifetime.abort(new Error(`${this.options.name}: plugin disposed`))
|
||||
try {
|
||||
|
||||
@@ -1,28 +1,46 @@
|
||||
/**
|
||||
* Credential-free account views that CLI plugins stream to the Plugins page; each plugin supplies its own account,
|
||||
* operation, and failure types.
|
||||
*/
|
||||
|
||||
import type { Branded } from '@deepseek-ai/dsh-brand'
|
||||
|
||||
/** Identifies one Host-owned account operation across the plugin's subscribers. */
|
||||
export type CliOperationId = Branded<'CliOperationId'>
|
||||
|
||||
/**
|
||||
* The account operation in progress. `checking` and `cancelling` are the runtime's phases;
|
||||
* `Phase` adds the plugin's own. Links are HTTPS URLs on the plugin's trusted hosts.
|
||||
*/
|
||||
export interface CliOperation<Kind extends string, Phase extends string> {
|
||||
readonly id: CliOperationId
|
||||
readonly kind: Kind
|
||||
readonly phase: Phase | 'checking' | 'cancelling'
|
||||
/** Whether the runtime cancels the operation in its current phase. */
|
||||
readonly cancellable: boolean
|
||||
readonly authorizationUrl?: string
|
||||
}
|
||||
|
||||
/** Classified facts about the last command a failed operation ran; plugins extend it with allowlisted fields only. */
|
||||
export interface CliCommandFailure<Command extends string = string> {
|
||||
/** The plugin's identifier for the command, not its native arguments. */
|
||||
readonly command: Command
|
||||
/** The observed exit code; null when the command produced no exit, as when lookup or spawn failed. */
|
||||
readonly exitCode: number | null
|
||||
}
|
||||
|
||||
/** The most recent finished operation, kept until another one starts. */
|
||||
export interface CliOperationResult<Kind extends string, Failure extends CliCommandFailure = CliCommandFailure> {
|
||||
readonly id: CliOperationId
|
||||
readonly kind: Kind
|
||||
readonly outcome: 'succeeded' | 'cancelled' | 'failed'
|
||||
/** Present only for a failed operation that ran a command; does not imply rollback or a safe retry. */
|
||||
readonly failure?: Failure
|
||||
}
|
||||
|
||||
/** The complete view a Remote client replaces on every change. */
|
||||
export interface CliAccountView<Account, Kind extends string, Phase extends string, Failure extends CliCommandFailure = CliCommandFailure> {
|
||||
/** The account as the plugin last published it. */
|
||||
readonly account: Account
|
||||
readonly operation?: CliOperation<Kind, Phase>
|
||||
readonly result?: CliOperationResult<Kind, Failure>
|
||||
|
||||
Reference in new issue
Block a user