chore: 纳入本地 Dify 1.19.0 源码及品牌与免登改动

演示目录只保留可重建的源码。运行密钥、数据卷、依赖和带口令的本地配置不进入仓库。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
wuzilongandCursor committed 2026-11-18 13:59:25 +08:00
1 parent 60158935f4
commit 6519682885
15831 files changed
+3063428

No files matched your search

+1
View File
@@ -0,0 +1 @@
1.4.2
+19
View File
@@ -0,0 +1,19 @@
dist/
coverage/
node_modules/
*.tsbuildinfo
.vitest-cache/
docs/specs/
context/
# E2E test env (contains tokens/credentials — use .env.e2e.example instead)
.env.e2e
# Generated / runtime artifacts
oclif.manifest.json
npm-shrinkwrap.json
tmp/
test/**/*.ts.map
test/**/*.js.map
test/**/*.js
test/**/*.d.ts
.token-cache.json
.vitest/
+28
View File
@@ -0,0 +1,28 @@
# AGENTS.md — difyctl (TypeScript CLI)
This package is the ESM TypeScript implementation of `difyctl`. Use the Node.js version pinned in `package.json`. Development also requires the Bun version pinned in `.bun-version`; command-tree generation and the `dev`, `test`, and `build` pre-scripts invoke it. Read [`ARD.md`] before adding a command or changing shared CLI infrastructure. Read `src/commands/AGENTS.md` for command-folder and registry rules.
## Architecture Boundaries
- Every command extends `Command` (`src/plugins/commands/command.ts`) and declares no `needs` of its own; it reads whatever plugin services it uses directly through `ctx.get(...)` inside `run(input, ctx)`.
- Plugins under `src/plugins/` (`argv global-flags env config session token catalog http ops io commands`) own state. A plugin's `build()` closes over its own cache or loaded document; nothing outside a plugin reaches into another plugin's internals. Outside a plugin folder, import only `@/plugins/<name>` and use the service from `ctx.get(...)`; the command framework (`plugins/commands/command.ts`, `cancel.ts`, `registry.ts`) and the argv parser (`plugins/argv/parse.ts`) are the only modules imported directly.
- `src/protocol/` and `src/call/` are pure modules: catalog-shape logic (kinds, bind, pins, fold) and the `call` flag table, request-building and rendering, with no op-specific branching anywhere under `src/call/` — kind and bind dispatch go through the tables in `src/protocol/` and `src/call/render/`, keyed by the catalog's own `kind`/`bind` values, never by operation id.
- Preserve exit codes and the JSON output contract during refactors. Do not add dependencies or compatibility shims unless the task explicitly requires them.
- Local YAML files go through `localFile` (`src/store/local-file.ts`), one schema each, no versions. Never change a key's name/type/meaning; add a new key (it may fall back to the old one).
- `ARD.md` owns CLI code structure. Keep behavior aligned with the real mock-server (`test/fixtures/dify-mock/`) behavior tests.
## Commands
Run package scripts from `cli/`:
- Source CLI: `pnpm dev <command> [args...]`
- Tests: `pnpm test`
- Build: `pnpm build`
- Build a local binary: `pnpm build:bin:local` (pins `DIFYCTL_CHANNEL=dev` so it does not self-report the release channel)
- Regenerate and verify the registry: `pnpm tree:gen` and `pnpm tree:check`
Run the scoped static check from the repository root with `vp check cli`.
Behavior tests use the real Hono server under `test/fixtures/dify-mock/`; do not replace it with `nock`, `msw`, or `fetchMock`. Keep tests colocated with their source files.
[`ARD.md`]: ARD.md
+201
View File
@@ -0,0 +1,201 @@
# ARD — Architecture & Design Reference
Onboarding ref for `dify/cli/` contributors. Cover canonical patterns, layer contracts, scaffolding recipe, dev workflow, anti-patterns. Read before adding command or touching shared infra.
---
## Layout
```
src/
kernel/ plugin + Context primitives — no CLI knowledge
plugins/ argv global-flags env config session token catalog http ops output io commands — the 12 services, one folder each; index.ts is the plugin and the only file anything outside the folder imports
argv/ the invocation's tokens as a context input, plus the argv parser (parse.ts, framework shared by global-flags and commands)
global-flags/ flags any command accepts (`--verbose`, `--json`), parsed off argv before the command is resolved
catalog/ the cached catalog document: types, parseCatalog, op lookup
http/ the authenticated fetch wrapper with the catalog fingerprint header; refetches on 412, and on 404 when the catalog moved
ops/ the catalog as a command tree (refetched on request); command.ts adapts one op to a Command, tree.ts builds their command tree
output/ output mode per stream: text on a terminal, JSON in a pipe; `--json` or `DIFY_OUTPUT` forces one
io/ the one way anything is printed
commands/ command pipeline plus the command framework (command.ts, cancel.ts, registry.ts) every command imports; help.ts shapes the help views, text.ts renders them for a terminal
protocol/ pure catalog-shape logic: kinds, bind, pins, fold, shape (a JSON Schema as one of ten shapes), op-id (dotted id and its spaced words) — no I/O
discovery/ pure id tree and ranked search over commands and ops — no I/O
call/ the `call` flag table; JSON and SSE response decoding; builds a request from a resolved op + validated input; renders the response by kind
commands/ one folder per command leaf; index.ts is the only file the registry discovers
net/ fetch init and proxy dispatcher, shared by the http plugin and the pre-login device flow
store/ config/session/token file and keychain persistence
sys/ the process edges — env, argv, exit, platform paths; io/ holds streams.ts, color.ts and view.ts (a JSON value paired with its text form, the mode picks one)
skills/ the one embedded difyctl skill (or a local folder) and its installer
```
---
## Kernel
A plugin is `{ name, needs, build(ctx) }`. `needs` is a list of the other plugin objects it reads through `ctx.get(...)` — an array of the actual plugin values, not strings or classes, so a plugin literally names its dependencies and TypeScript checks `build`'s `ctx` against that list (`src/kernel/plugin.ts`).
`Context` (`src/kernel/context.ts`) builds services lazily: `ctx.get(plugin)` runs `plugin.build(ctx)` the first time that plugin is requested, caches the result, and returns the cached service on every later call in the same invocation. A plugin never builds if nothing asks for it. `needs` is only the compile-time allow-list for that plugin's `ctx.get`; the kernel never walks it, so declaring `needs: BASE_PLUGINS` on the `commands` plugin costs nothing until a command actually calls `ctx.get` on one of them (`version` logged out builds six plugins, never `http`).
State stays with its owner. A plugin's `build()` closes over its own state (an in-memory cache, a loaded config document); nothing outside reaches into it — code that needs it calls `ctx.get(thatPlugin)` again and gets the same cached instance.
`ctx.defer(fn)` queues a cleanup to run after the command finishes (for example, aborting a streaming call's `AbortController` on `SIGINT`), instead of scattering `try`/`finally` through command bodies.
There is no event bus and no listener registration. Plugins that need to react to something call `ctx.get` on the plugin that has it; there is no subscribe/publish path to keep in sync.
The one `commands` plugin (`src/plugins/commands/index.ts`) needs `BASE_PLUGINS` (`global-flags env config session token catalog http ops io`) and its `build()` returns `{ run }`. `runPipeline` takes the argv left over by `global-flags`, resolves the typed `Command` from the generated tree, parses those tokens against that command's Zod `input` schema, and calls `run(input, ctx)` — the pipeline never branches on which command it is.
A plugin's folder is private. Code outside it imports only the plugin's `index.ts` (`@/plugins/<name>`) and reaches the plugin's behaviour through `ctx.get(plugin)`; a helper two plugins share is exposed on a service, and a helper only commands use lives outside `src/plugins/`. The two exceptions are contracts rather than services: the command framework in `plugins/commands/` (`Command`, `Outcome`, `runSignal`, the tree types) and the argv parser in `plugins/argv/parse.ts`.
Global flags are one Zod object in `src/plugins/global-flags/index.ts`. The plugin pulls the flags it knows out of the `argv` input, exposes their values as `flags` and the remaining tokens as `rest`; any plugin or command reads a global flag through `ctx.get(globalFlags)`, never by scanning argv. Which flag wins over an env var or a config key is decided in the plugin that owns the setting, not here.
Help is the row: `commandRow(Ctor, path)` (`src/plugins/commands/describe.ts`) is the one function that renders a command's `--help` output and its entry in `help --full` — there is no separate help-text template. Catalog operations are commands in the same tree, so `entriesOf(tree)` in `plugins/commands/help.ts` feeds the map, namespace listings and search (`src/discovery/`) from one list; words no command claims go to `discover` in the pipeline. `plugins/commands/text.ts` renders the same values for a terminal through a section table.
Tests substitute one plugin's service directly: `new Context([[plugin, mockService]])` seeds the cache so `ctx.get(plugin)` returns the mock without building the real one.
---
## New command scaffold
1. Create the folder: `src/commands/<topic>/<verb>/` (or `src/commands/<verb>/` for a top-level command like `login`).
2. Write `index.ts`: a default-exported class extending `Command<typeof INPUT>` with static `summary`, `effect` (`'read' | 'write' | 'destructive'`, default `'read'`), `input` (a Zod object), optional `positional` and `examples`, and an instance `run(input, ctx)` that returns the value to print — or an `Outcome` when the command needs a non-zero exit or has already written its own output.
3. Run `pnpm tree:gen` to add the command to `src/commands/tree.generated.ts`.
4. Run `pnpm tree:check` (also gated in CI) to confirm the generated tree matches the command folders.
---
## Error handling
Throw `BaseError`. Never throw raw `Error` for domain failures.
```typescript
import { BaseError } from '@/errors/base'
import { ErrorCode } from '@/errors/codes'
throw new BaseError({
code: ErrorCode.UsageMissingArg,
message: 'workspace id required',
hint: "pass --workspace-id or run 'difyctl use workspace <id>'",
})
```
`ErrorCode` is the exhaustive error-code object; do not scatter raw code strings. `exitFor(code)` maps it to a process exit code, and `BaseError.toEnvelope()` serializes it as the one JSON error line on stderr.
| Exit | Meaning |
| ---- | ------------------------------------------------ |
| 0 | Success |
| 1 | Generic error |
| 2 | Usage error (bad flag, missing or invalid input) |
| 4 | Auth error (not logged in, forbidden) |
| 6 | Catalog error (unavailable, or unknown op id) |
| 7 | Rate limited |
New error code: add to `ErrorCode` and map it to an `ExitCode` in `codes.ts`. Never scatter exit codes inline.
---
## Output
Everything the CLI prints goes through the `io` plugin's service, never through a stream directly. Three writes cover every case; a new output format or a `--quiet` flag is a change inside this one plugin.
```typescript
export type IOService = Readonly<{
document: (value: Printable | View) => Promise<void> // stdout: results, help
emit: (value: Printable | View, channel: ChannelValue) => Promise<void> // either stream
notice: (text: string) => void // one text line on stderr: warnings, progress
raw: (chunk: string | Buffer) => Promise<void> // bytes as given: a text-kind body
streams: IOStreams // stdin and the TTY flags
}>
```
`Printable` (a JSON primitive, an array, or a plain object) is what a command may return and what `document` accepts. A `View` (`sys/io/view.ts`) is a `Printable` plus its text form; help and errors pass one, and the stream's mode picks which is written. Results and streams are JSON in every mode. Streamed events go through `raw`, one per line. stdout writes use the callback form so a closed pipe reaches `printEnvelope` as a rejection and the run ends at exit 0. `printEnvelope` emits the envelope through the same service on the err channel.
`IOStreams` is the raw layer underneath: `realStreams()` wraps `process.std*` in production, `bufferStreams()` captures output in tests, and `ioService(streams)` wraps either.
---
## Testing
Keep tests beside the owner as `*.test.ts`. When a command delegates to a pure module (`call/`, `protocol/`), test that module directly. Test the command class or the `commands` pipeline when argument parsing, help, or command wiring is the observable contract. Establish a failing case first when practical for behavior changes and bug fixes.
### dify-mock fixture server
`test/fixtures/dify-mock/server.ts` mirrors `/openapi/v1/*` and the catalog endpoint. Each test starts an isolated instance:
```typescript
import { startMock } from '../../../test/fixtures/dify-mock/server.js'
const mock = await startMock({ scenario: 'happy' })
// ... test against mock.url ...
await mock.stop()
```
`happy` (default) is the standard fixture set: 4 apps across 2 workspaces, 2 workspaces, 1 active session. See `Scenario` in `scenarios.ts` for the full union — auth failures, rate limiting, catalog-fingerprint mismatches, HITL pauses, pending imports, and more.
New scenario: extend the `Scenario` union in `scenarios.ts`, branch in the relevant handler. No per-test mocks — one fixture surface keeps tests aligned with the real API.
### Assertions
Inline string/regex/JSON checks — no golden files.
```typescript
expect(JSON.parse(out).data).toHaveLength(2)
```
---
## Scripts
| Command | When to run |
| ----------------------- | ---------------------------------------------- |
| `pnpm dev <cmd> [args]` | Run CLI from source during dev |
| `pnpm test` | Full vitest suite — run before every commit |
| `pnpm test:coverage` | Coverage report |
| `vp check cli` | Scoped static check from the repository root |
| `vp check --fix cli` | Scoped static fixes from the repository root |
| `pnpm build` | Production bundle (`vp pack`) |
| `pnpm tree:gen` | Regenerate `src/commands/tree.generated.ts` |
| `pnpm tree:check` | Verify the generated tree matches the commands |
| `pnpm build:bin` | Cross-compile standalone binaries via Bun (CI) |
| `pnpm build:bin:local` | Same, pinned to the `dev` channel |
**`pnpm tree:gen` rule:** run after adding, removing, or renaming any command. The generated `tree.generated.ts` is the runtime command registry; a stale tree makes commands invisible at runtime. It also runs through `prebuild`, `predev`, and `pretest`.
**README hand-maintained.** When adding a command, update the command table in `README.md` manually.
---
## Lint rules that catch contributors
The repository runs Vite+ Oxlint as the primary code-quality linter, an explicit ESLint config for unsupported cases, and Vite+ Oxfmt for formatting. The fallback config does not depend on the Antfu ESLint config.
| Rule | What it catches |
| ---------------------------------- | -------------------------------------------------- |
| `perfectionist/sort-named-imports` | Alphabetical, case-insensitive |
| `perfectionist/sort-imports` | Relative imports last; `import type` first |
| `antfu/consistent-chaining` | Long `.foo().bar().baz()` must split across lines |
| `unicorn/no-new-array` | Use `Array.from({ length: n })` not `new Array(n)` |
| `noUncheckedIndexedAccess` (tsc) | `arr[i]` is `T \| undefined`; guard before use |
Run `vp check --fix cli` from the repository root for scoped formatting, lint, and TypeScript fixes and diagnostics.
---
## PR conventions
- One feature, one PR. Bundle test + impl + doc update.
- Commit style: `<type>(cli): <imperative subject>`. Types: `feat`, `fix`, `refactor`, `docs`, `chore`. Body explains why if non-obvious.
- Plan/spec/superpowers files do not ship in CLI commits.
- Verify diff before committing — `.local.json` and `.vitest-cache/` gitignored but check anyway.
---
## Anti-patterns
| Pattern | Do instead |
| ----------------------------------------------------------- | ---------------------------------------------------------------------- |
| Raw string error codes `'not_logged_in'` | `ErrorCode.NotLoggedIn` |
| Long positional arg lists | A Zod `input` object with named fields |
| `if (kind === 'sse') { ... } else if (kind === 'list') ...` | A `Record<Kind, Renderer>` dispatch table (see `call/render/index.ts`) |
| A command reaching into another plugin's closed-over state | `ctx.get(thatPlugin)` — the cached service, not its internals |
| `console.log` in `src/` | Return the value from `run()`; the pipeline prints it |
| New dependency without approval | Check first |
+148
View File
@@ -0,0 +1,148 @@
# difyctl
CLI client for the [Dify] platform. Browser device-flow sign-in, then a server-published catalog of operations you discover and call at run time, each one a command. Results are JSON; help and errors are text on a terminal, JSON in a pipe.
## Install
difyctl ships as assets on Dify releases. The installer picks the build from the latest release; set `DIFY_VERSION` to match your Dify server:
```sh
curl -fsSL https://raw.githubusercontent.com/langgenius/dify/main/cli/scripts/install-cli.sh | sh
```
Windows (PowerShell): `irm https://raw.githubusercontent.com/langgenius/dify/main/cli/scripts/install.ps1 | iex`.
The binary goes to `$HOME/.local/bin` (Windows: `%LOCALAPPDATA%\difyctl\bin`). Every installer accepts `DIFYCTL_INSTALL_DIR` (the bin folder itself) and `DIFYCTL_PREFIX` (the folder above it, so the binary lands in `<prefix>/bin`); `DIFYCTL_INSTALL_DIR` wins when both are set.
## Install (edge, internal)
Per-commit `edge` builds are published to Cloudflare R2. The installer script lives in this repo; binaries are fetched from R2 via `DIFYCTL_R2_BASE` (shared internally):
```sh
curl -fsSL https://raw.githubusercontent.com/langgenius/dify/main/cli/scripts/install-r2.sh | DIFYCTL_R2_BASE=<BASE> sh
```
| Env | Default | Purpose |
| ----------------------- | ------------------ | --------------------------------------------------------------------------------------------------------------- |
| `DIFYCTL_R2_BASE` | — (required) | R2 public base, e.g. `https://pub-….r2.dev`. |
| `DIFYCTL_CHANNEL` | `edge` | Channel to install. |
| `DIFYCTL_INSTALL_DIR` | `$HOME/.local/bin` | Directory the binary is written to (`<dir>/difyctl`). On Windows the default is `%LOCALAPPDATA%\difyctl\bin`. |
| `DIFYCTL_PREFIX` | `$HOME/.local` | Used as `<prefix>/bin` when `DIFYCTL_INSTALL_DIR` is unset. On Windows the default is `%LOCALAPPDATA%\difyctl`. |
| `DIFYCTL_VERSION` | latest | Pin an exact published version. |
| `DIFYCTL_COMMIT` | latest | Pin by git commit (short or full sha). |
| `DIFYCTL_R2_PREFIX` | `difyctl` | R2 key root for the pointer JSONs (`manifest.json` / `index.json`). |
| `DIFYCTL_R2_BIN_PREFIX` | `difyctl/bin` | R2 key root for binaries (the lifecycle/TTL target). |
By default the channel pointer (latest build) is installed. Set `DIFYCTL_COMMIT` (e.g. `ce4af86`) or `DIFYCTL_VERSION` to install a specific past build — both resolve through the channel's `index.json`:
```sh
curl -fsSL https://raw.githubusercontent.com/langgenius/dify/main/cli/scripts/install-r2.sh | DIFYCTL_R2_BASE=<BASE> DIFYCTL_COMMIT=ce4af86 sh
```
Windows: `$env:DIFYCTL_R2_BASE='<BASE>'; irm https://raw.githubusercontent.com/langgenius/dify/main/cli/scripts/install-r2.ps1 | iex` (same env vars, e.g. `$env:DIFYCTL_COMMIT='ce4af86'`).
Re-run to upgrade. For tagged `rc`/`stable` builds, use the GitHub installer (`install-cli.sh` / `install.ps1`), which resolves releases via the GitHub API. That API caps unauthenticated requests at 60/hour per IP; behind a shared NAT or in CI, set `GITHUB_TOKEN` (or `GH_TOKEN`) to raise it to 5000/hour — the installer sends it as a bearer token.
## Quickstart
```sh
difyctl login --server https://dify.example.com # opens the browser; approve the device code shown
difyctl help # the map: every command and operation namespace
difyctl help chatbot # search commands and operations by plain words
difyctl get workspace # workspaces visible to this account
difyctl describe workspace # the workspace difyctl uses
difyctl get console_app --limit 5 # list apps
difyctl run console_app workflow --app-id <id> --inputs @vars.json --stream
```
difyctl has no built-in business commands. Every operation the server publishes is a command: `run.console_app.workflow` is `difyctl run console_app workflow`, and its input fields are flags (`--app-id`, `--inputs`). A field named like one of difyctl's own flags (`input`, `stream`, `only`, `output`, `verbose`, `json`, `help`) is passed through `--input`. The table lists the local commands; `difyctl help` lists the server's too. See [Agent skill] for the discovery flow.
## Commands
| Command | Purpose |
| -------------------------- | ------------------------------------------------------ |
| `login` | Log in via the OAuth device flow |
| `logout` | Log out of the current session |
| `version` | Print the client and (if logged in) server versions |
| `use workspace <id>` | Pin this device to a workspace you belong to |
| `get config [key]` | Print the local config, or one key |
| `set config <key> <value>` | Set a local config value |
| `unset config <key>` | Remove a local config value, restoring its default |
| `refresh cache` | Refetch the server catalog and replace the local cache |
| `delete cache` | Delete the local server catalog cache |
| `install skills <dir>` | Write the difyctl skill into a skills root (`--from`) |
`login` needs `--server`; there is no default server. It blocks until the browser approval arrives. An agent uses `--no-wait` instead: it gives the user the URL and code, then runs `login --resume` after the user approves. If it sets `DIFY_CONFIG_DIR`, it sets it on every call.
`--verbose` is global: it may appear on any command, and it keeps the raw server
response in the error envelope instead of dropping it.
`difyctl help` covers local commands and server operations as one tree. Bare, it prints the map. `difyctl help <namespace>` lists one namespace (the bare namespace, `difyctl get`, does the same), `difyctl help <words>` searches by plain words, and `difyctl help <id>` prints one descriptor, the same as `<command> --help`; the id may be dotted or spaced. `--all` adds hidden entries, `--full` on the bare `help` prints every descriptor. Help and errors are text on a terminal and JSON in a pipe; `--json` or `DIFY_OUTPUT=json` forces JSON. Results and streams are always JSON.
## Agent skills
difyctl ships one skill, `difyctl`, built into the binary. It teaches the discovery flow — `help` to see the map or search, `help <id>` to inspect one operation, then the operation's own command to run it — so it stays correct as the server's catalog grows. The skill is a tree of linked docs under [`skills/difyctl/`].
- `difyctl install skills <dir> [--from <folder>]` — write the skill into `<dir>`, the agent's skills root: the folder that holds one subfolder per skill, for example `~/.claude/skills` for Claude Code or `~/.codex/skills` for Codex. The `difyctl` folder is replaced whole. It works offline. `--from` installs a local skill folder instead of the built-in one.
difyctl does not detect agents. You name the root, and re-running the same command refreshes the copies.
The same files install through the Vercel skills installer: `npx skills add langgenius/dify --skill difyctl -g`. Always pass `--skill`; without it the installer also offers the contributor skills under `.agents/skills/`.
## Configuration
| OS | Config path |
| ------- | -------------------------------------------- |
| Linux | `${XDG_CONFIG_HOME:-$HOME/.config}/difyctl/` |
| macOS | `$HOME/.config/difyctl/` |
| Windows | `%APPDATA%\difyctl\` |
`get config [key]` prints the whole local config or one key; `set config <key> <value>` and `unset config <key>` change it. The only config key today is `http.timeout` (request timeout in milliseconds).
Tokens use the OS keychain by default, falling back to `tokens.yml` in the config folder on hosts without one. On Linux without a DBus session (`DBUS_SESSION_BUS_ADDRESS` unset), the keychain would only hold the token until the session ends, so difyctl uses `tokens.yml` there too; `login --no-keyring` chooses the file outright. The catalog cache is kept in the config folder under `catalog/`; `DIFY_CACHE_DIR` is no longer used. Config and cache files are written `0600`, their directory `0700`.
| Env var | Effect |
| ------------------- | ----------------------------------------------------------- |
| `DIFY_SERVER` | Server base URL; with `DIFY_TOKEN`, skips interactive login |
| `DIFY_TOKEN` | Bearer token; requires `DIFY_SERVER` |
| `DIFY_WORKSPACE_ID` | Overrides the locally pinned workspace |
| `DIFY_OUTPUT` | `json` or `text`; overrides the terminal/pipe detection |
| `DIFY_CONFIG_DIR` | Overrides the config directory |
Resource access tokens can also be passed through `DIFY_TOKEN`. They can list
their own workspace and discover only apps bound to that token; workspace
details, members, and workspace switching remain unavailable.
## Streaming
Pass `--stream` on a streaming operation to print every event as one JSON line, instead of folding the whole run into a single result object:
```sh
difyctl run console_app chat --app-id … --query hello --inputs '{}' --stream
```
`--only <event>` filters the streamed events to the named event types; repeat it to keep more than one. Without `--stream`, a streaming operation's events fold into `{status, text, outputs?, message_id?, conversation_id?, run_id?, error?, hints}`.
## Exit codes
| Code | Meaning |
| ---- | -------------------------------------------- |
| 0 | Success |
| 1 | Error |
| 2 | Usage or input error |
| 4 | Not logged in, or forbidden |
| 6 | Catalog unavailable, or unknown operation id |
| 7 | Rate limited |
## Contributing
See [`ARD.md`] for architecture patterns, scaffolding recipe, dev workflow.
## License
Apache-2.0.
[Agent skill]: #agent-skills
[Dify]: https://dify.ai
[`ARD.md`]: ARD.md
[`skills/difyctl/`]: ../skills/difyctl
+15
View File
@@ -0,0 +1,15 @@
#!/usr/bin/env -S bun
import { resolveBuildInfo } from '../scripts/lib/resolve-buildinfo.ts'
const info = resolveBuildInfo({
env: { ...process.env, DIFYCTL_CHANNEL: process.env.DIFYCTL_CHANNEL ?? 'dev' },
})
globalThis.__DIFYCTL_VERSION__ = info.version
globalThis.__DIFYCTL_COMMIT__ = info.commit
globalThis.__DIFYCTL_BUILD_DATE__ = info.buildDate
globalThis.__DIFYCTL_CHANNEL__ = info.channel
globalThis.__DIFYCTL_COMPILED__ = false
const { main } = await import('../src/main.ts')
process.exitCode = await main(process.argv.slice(2))
+20
View File
@@ -0,0 +1,20 @@
#!/usr/bin/env node
import { main } from '../src/main.js'
import { cancel } from '../src/plugins/commands/cancel.js'
const EPIPE = 'EPIPE'
// SIGINT unwinds the run through the shared controller; the exit code is whatever
// the command settles on, since 130 is outside the frozen taxonomy.
process.once('SIGINT', cancel)
// A reader that closed stdout (`| head`) still emits on the stream after the write
// callback has already reported it. Swallowing only EPIPE keeps that from turning a
// finished run into an unhandled 'error' event.
process.stdout.on('error', (err: NodeJS.ErrnoException) => {
if (err.code !== EPIPE) throw err
})
void (async () => {
process.exitCode = await main(process.argv.slice(2))
})()
+102
View File
@@ -0,0 +1,102 @@
{
"name": "@langgenius/difyctl",
"version": "1.19.0",
"description": "Dify command-line interface",
"license": "Apache-2.0",
"files": [
"README.md",
"bin",
"dist"
],
"type": "module",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js"
}
},
"scripts": {
"build": "vp pack",
"dev": "bun bin/dev.js",
"test": "vp test",
"test:coverage": "vp test --coverage",
"test:e2e": "vp test --config vitest.e2e.config.ts",
"test:e2e:smoke": "vp test --config vitest.e2e.config.ts --testNamePattern \"\\[P0\\]\"",
"test:e2e:local": "DIFY_E2E_MODE=local vp test --config vitest.e2e.config.ts",
"type-check": "tsrs --noEmit",
"tree:gen": "bun scripts/generate-command-tree.ts",
"tree:check": "bun scripts/generate-command-tree.ts --check",
"prebuild": "pnpm tree:gen",
"predev": "pnpm tree:gen",
"pretest": "pnpm tree:gen",
"ci": "pnpm tree:check && pnpm test:coverage && pnpm build",
"clean": "rm -rf dist node_modules/.cache",
"smoke": "bun scripts/run-smoke.ts",
"version:info": "bun scripts/print-buildinfo.ts",
"build:bin": "scripts/release-build.sh",
"build:bin:local": "DIFYCTL_CHANNEL=dev scripts/release-build.sh"
},
"dependencies": {
"@napi-rs/keyring": "catalog:",
"ajv": "catalog:",
"eventsource-parser": "catalog:",
"js-yaml": "catalog:",
"lockfile": "catalog:",
"open": "catalog:",
"picocolors": "catalog:",
"undici": "catalog:",
"zod": "catalog:"
},
"devDependencies": {
"@dify/tsconfig": "workspace:*",
"@hono/node-server": "catalog:",
"@types/lockfile": "catalog:",
"@types/node": "catalog:",
"@typescript/native": "catalog:",
"@vitest/coverage-v8": "catalog:",
"hono": "catalog:",
"tsrs": "catalog:",
"typescript": "catalog:",
"vite": "catalog:",
"vite-plus": "catalog:",
"vitest": "catalog:"
},
"engines": {
"node": "^24.22.1"
},
"difyctl": {
"channel": "stable",
"release": {
"tagPrefix": "difyctl-v",
"binName": "difyctl",
"checksumsSuffix": "-checksums.txt",
"targets": [
{
"id": "linux-x64",
"bunTarget": "bun-linux-x64",
"exe": false
},
{
"id": "linux-arm64",
"bunTarget": "bun-linux-arm64",
"exe": false
},
{
"id": "darwin-x64",
"bunTarget": "bun-darwin-x64",
"exe": false
},
{
"id": "darwin-arm64",
"bunTarget": "bun-darwin-arm64",
"exe": false
},
{
"id": "windows-x64",
"bunTarget": "bun-windows-x64",
"exe": true
}
]
}
}
}
@@ -0,0 +1,20 @@
# Cross-arch keyring prebuilds for difyctl release builds.
#
# Appended onto pnpm-workspace.yaml in CI *before* the dependency install so a
# single `pnpm install` pulls the @napi-rs/keyring native bindings for every
# release target, letting `bun build --compile` embed the correct per-target
# `.node` into each standalone binary.
#
# Kept out of the committed pnpm-workspace.yaml on purpose: setting it as a
# workspace default would pull every foreign-arch prebuild into ordinary dev
# installs. pnpm only honors supportedArchitectures from pnpm config files
# (workspace yaml / .npmrc parsed as pnpm config), and only on the install that
# first populates node_modules — a second pass is a no-op.
supportedArchitectures:
os:
- linux
- darwin
- win32
cpu:
- x64
- arm64
+368
View File
@@ -0,0 +1,368 @@
#!/usr/bin/env bun
import { Buffer } from 'node:buffer'
/**
* e2e-provision.ts
*
* Standalone pre-flight script for CI parallel e2e jobs.
*
* What it does (mirrors global-setup.ts, but without vitest):
* 1. Console login → cookie + CSRF token
* 2. Mint a primary bearer token (or validate a cached/pre-set one)
* 3. Discover primary + secondary workspaces
* 4. Provision all DSL fixture apps (idempotent — reuses existing ones)
* 5. Write GITHUB_OUTPUT (token, workspace IDs, all app IDs)
* so downstream jobs can skip re-minting and re-provisioning.
*
* Usage (in CI):
* bun scripts/e2e-provision.ts
*
* Required env vars:
* DIFY_E2E_HOST, DIFY_E2E_EMAIL, DIFY_E2E_PASSWORD
*
* Optional:
* DIFY_E2E_EDITION (ee | ce, default: ee)
* DIFY_E2E_TOKEN pre-minted token — skips device-flow mint
*
* Output file:
* .provision-output.json (also written to GITHUB_OUTPUT if set)
*/
import { appendFile, readFile } from 'node:fs/promises'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
// ── Env ──────────────────────────────────────────────────────────────────────
const host = process.env.DIFY_E2E_HOST ?? ''
const email = process.env.DIFY_E2E_EMAIL ?? ''
const password = process.env.DIFY_E2E_PASSWORD ?? ''
const edition = (process.env.DIFY_E2E_EDITION ?? 'ee').toLowerCase() as 'ee' | 'ce'
const preToken = process.env.DIFY_E2E_TOKEN ?? ''
if (!host || !email || !password) {
console.warn('[provision] Missing required env: DIFY_E2E_HOST, DIFY_E2E_EMAIL, DIFY_E2E_PASSWORD')
process.exit(1)
}
const base = host.replace(/\/$/, '')
// ── Helpers ───────────────────────────────────────────────────────────────────
function sleep(ms: number) {
return new Promise((r) => setTimeout(r, ms))
}
async function consoleLogin(): Promise<{ cookieString: string; csrfToken: string }> {
const passwordB64 = Buffer.from(password, 'utf8').toString('base64')
const res = await fetch(`${base}/console/api/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password: passwordB64, remember_me: false }),
signal: AbortSignal.timeout(15_000),
})
if (!res.ok) throw new Error(`console/api/login failed: HTTP ${res.status}`)
const setCookies = res.headers.getSetCookie?.() ?? []
const cookiePairs = setCookies.map((c) => c.split(';')[0] ?? '')
const cookieString = cookiePairs.join('; ')
// cookie names may have __Host- prefix on HTTPS deployments
const csrfPair = cookiePairs.find((p) => p.includes('csrf_token='))
const csrfToken = csrfPair
? csrfPair.slice(csrfPair.indexOf('csrf_token=') + 'csrf_token='.length)
: ''
return { cookieString, csrfToken }
}
async function validateToken(token: string): Promise<boolean> {
try {
const res = await fetch(`${base}/openapi/v1/account/sessions`, {
headers: { Authorization: `Bearer ${token}` },
signal: AbortSignal.timeout(10_000),
})
return res.ok
} catch {
return false
}
}
async function mintToken(cookieStr: string, csrf: string, label: string): Promise<string> {
// Step 1: device code
const codeRes = await fetch(`${base}/openapi/v1/oauth/device/code`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ client_id: 'difyctl', device_label: label }),
signal: AbortSignal.timeout(15_000),
})
if (!codeRes.ok) throw new Error(`device/code failed: HTTP ${codeRes.status}`)
const { device_code, user_code } = (await codeRes.json()) as {
device_code: string
user_code: string
}
// Step 2: approve (with retry)
let approveRes: Response | undefined
for (let i = 1; i <= 5; i++) {
approveRes = await fetch(`${base}/openapi/v1/oauth/device/approve`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Cookie: cookieStr, 'X-CSRFToken': csrf },
body: JSON.stringify({ user_code }),
signal: AbortSignal.timeout(10_000),
})
if (approveRes.ok) break
if (approveRes.status !== 429 && approveRes.status < 500) break
console.warn(`[provision] device/approve HTTP ${approveRes.status}; retry ${i}/5 in ${i * 2}s`)
await sleep(i * 2_000)
}
if (!approveRes?.ok) throw new Error(`device/approve failed: HTTP ${approveRes?.status}`)
// Step 3: exchange token
const tokenRes = await fetch(`${base}/openapi/v1/oauth/device/token`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ device_code, client_id: 'difyctl' }),
signal: AbortSignal.timeout(10_000),
})
if (!tokenRes.ok) throw new Error(`device/token failed: HTTP ${tokenRes.status}`)
const body = (await tokenRes.json()) as { token?: string }
if (!body.token) throw new Error(`device/token missing token: ${JSON.stringify(body)}`)
return body.token
}
async function discoverWorkspaces(cookieStr: string, csrf: string) {
const res = await fetch(`${base}/console/api/workspaces`, {
headers: { Cookie: cookieStr, 'X-CSRF-Token': csrf },
signal: AbortSignal.timeout(10_000),
})
if (!res.ok) throw new Error(`list workspaces failed: HTTP ${res.status}`)
const data = (await res.json()) as { workspaces?: Array<{ id: string; name: string }> }
const all = data.workspaces ?? []
if (edition === 'ee') {
const ws0 = all.find((w) => w.name === 'auto_test0')
const ws1 = all.find((w) => w.name === 'auto_test1')
if (!ws0) throw new Error('[provision] EE: workspace "auto_test0" not found')
console.warn(`[provision] EE primary: ${ws0.name} (${ws0.id})`)
console.warn(
`[provision] EE secondary: ${ws1?.name ?? 'reuses primary'} (${ws1?.id ?? ws0.id})`,
)
return { primaryWsId: ws0.id, primaryWsName: ws0.name, secondaryWsId: ws1?.id ?? ws0.id }
}
const auto = all
.filter((w) => w.name.toLowerCase().includes('auto'))
.sort((a, b) => a.name.localeCompare(b.name))
const primary = auto[0] ?? all[0]
if (!primary) throw new Error('[provision] No workspaces found')
return {
primaryWsId: primary.id,
primaryWsName: primary.name,
secondaryWsId: auto[1]?.id ?? primary.id,
}
}
async function provisionApps(
cookieStr: string,
csrf: string,
primaryWsId: string,
secondaryWsId: string,
): Promise<Record<string, string>> {
const mkH = (extra: Record<string, string> = {}) => ({
Cookie: cookieStr,
'X-CSRF-Token': csrf,
...extra,
})
const scriptDir = dirname(fileURLToPath(import.meta.url))
const fixturesDir = join(scriptDir, '..', 'test', 'e2e', 'fixtures', 'apps')
const NEEDS_PUBLISH = new Set(['workflow', 'advanced-chat', 'agent-chat'])
const APP_SPECS: Array<[string, string, string]> = [
['echo-chat.yml', 'DIFY_E2E_CHAT_APP_ID', primaryWsId],
['echo-workflow.yml', 'DIFY_E2E_WORKFLOW_APP_ID', primaryWsId],
['file-upload.yml', 'DIFY_E2E_FILE_APP_ID', primaryWsId],
['hitl-main.yml', 'DIFY_E2E_HITL_APP_ID', primaryWsId],
['hitl-external.yml', 'DIFY_E2E_HITL_EXTERNAL_APP_ID', primaryWsId],
['hitl-single-action.yml', 'DIFY_E2E_HITL_SINGLE_ACTION_APP_ID', primaryWsId],
['hitl-multi-node.yml', 'DIFY_E2E_HITL_MULTI_NODE_APP_ID', primaryWsId],
['file-chat.yml', 'DIFY_E2E_FILE_CHAT_APP_ID', primaryWsId],
...(edition === 'ee'
? [['ws2-workflow.yml', 'DIFY_E2E_WS2_APP_ID', secondaryWsId] as [string, string, string]]
: []),
]
let currentWs = ''
const results: Record<string, string> = {}
for (const [dslFile, envVar, wsId] of APP_SPECS) {
try {
// Switch workspace if needed
if (wsId !== currentWs) {
await fetch(`${base}/console/api/workspaces/switch`, {
method: 'POST',
headers: { ...mkH(), 'Content-Type': 'application/json' },
body: JSON.stringify({ tenant_id: wsId }),
signal: AbortSignal.timeout(10_000),
})
currentWs = wsId
}
const dsl = await readFile(join(fixturesDir, dslFile), 'utf8')
const appName =
(dsl.match(/^[ \t]+name:[ \t]*(\S[^\n]*)$/m) ?? [])[1]
?.trim()
.replace(/^['"]|['"]$/g, '') ?? dslFile
const appMode = (dsl.match(/^[ \t]+mode:[ \t]*(\S+)/m) ?? [])[1] ?? ''
// Find existing or import
const searchRes = await fetch(
`${base}/console/api/apps?name=${encodeURIComponent(appName)}&limit=50&page=1`,
{ headers: mkH(), signal: AbortSignal.timeout(10_000) },
)
const searchData = (await searchRes.json()) as { data?: Array<{ id: string; name: string }> }
let appId = searchData.data?.find((a) => a.name === appName)?.id
if (appId) {
console.warn(`[provision] ${dslFile}: exists id=${appId}`)
} else {
const importRes = await fetch(`${base}/console/api/apps/imports`, {
method: 'POST',
headers: { ...mkH(), 'Content-Type': 'application/json' },
body: JSON.stringify({ mode: 'yaml-content', yaml_content: dsl }),
signal: AbortSignal.timeout(30_000),
})
const importData = (await importRes.json()) as { app_id?: string; import_id?: string }
if (importRes.status === 202 && importData.import_id) {
const confirmRes = await fetch(
`${base}/console/api/apps/imports/${importData.import_id}/confirm`,
{
method: 'POST',
headers: mkH(),
signal: AbortSignal.timeout(15_000),
},
)
const confirmData = (await confirmRes.json()) as { app_id?: string }
appId = confirmData.app_id
} else {
appId = importData.app_id
}
if (!appId) throw new Error(`import failed: ${JSON.stringify(importData)}`)
console.warn(`[provision] ${dslFile}: imported id=${appId}`)
}
// Enable API
await fetch(`${base}/console/api/apps/${appId}/api-enable`, {
method: 'POST',
headers: { ...mkH(), 'Content-Type': 'application/json' },
body: JSON.stringify({ enable_api: true }),
signal: AbortSignal.timeout(10_000),
})
// Set public
await fetch(`${base}/console/api/enterprise/webapp/app/access-mode`, {
method: 'POST',
headers: { ...mkH(), 'Content-Type': 'application/json' },
body: JSON.stringify({ appId, accessMode: 'public' }),
signal: AbortSignal.timeout(10_000),
}).catch(() => {})
// Publish workflow
if (NEEDS_PUBLISH.has(appMode)) {
await fetch(`${base}/console/api/apps/${appId}/workflows/publish`, {
method: 'POST',
headers: { ...mkH(), 'Content-Type': 'application/json' },
body: JSON.stringify({ marked_name: 'e2e-provision', marked_comment: '' }),
signal: AbortSignal.timeout(20_000),
}).catch(() => {})
}
results[envVar] = appId
} catch (err) {
console.warn(`[provision] ${dslFile} skipped: ${err}`)
}
}
return results
}
async function writeOutputs(outputs: Record<string, string>) {
const ghOutput = process.env.GITHUB_OUTPUT
const lines = `${Object.entries(outputs)
.map(([k, v]) => `${k}=${v}`)
.join('\n')}\n`
// Always write local JSON for debugging
const { writeFile } = await import('node:fs/promises')
await writeFile('.provision-output.json', `${JSON.stringify(outputs, null, 2)}\n`, 'utf8')
console.warn('[provision] Written .provision-output.json')
if (ghOutput) {
await appendFile(ghOutput, lines, 'utf8')
console.warn(`[provision] Written ${Object.keys(outputs).length} outputs to GITHUB_OUTPUT`)
}
// Also print to stdout for visibility
console.warn('\n[provision] Outputs:')
for (const [k, v] of Object.entries(outputs))
console.warn(` ${k}=${v.slice(0, 30)}${v.length > 30 ? '…' : ''}`)
}
// ── Main ─────────────────────────────────────────────────────────────────────
async function main() {
console.warn(`[provision] Host=${base} Email=${email} Edition=${edition}`)
// 1. Login
const { cookieString, csrfToken } = await consoleLogin()
console.warn('[provision] Login OK')
// 2. Token
let primaryToken = preToken
if (primaryToken && (await validateToken(primaryToken))) {
console.warn(`[provision] Using pre-set token: ${primaryToken.slice(0, 20)}…`)
} else {
if (primaryToken) console.warn('[provision] Pre-set token invalid, minting fresh…')
primaryToken = await mintToken(cookieString, csrfToken, 'e2e-provision')
console.warn(`[provision] Minted token: ${primaryToken.slice(0, 20)}…`)
}
// 3. Discover workspaces
const { primaryWsId, primaryWsName, secondaryWsId } = await discoverWorkspaces(
cookieString,
csrfToken,
)
// 4. Provision apps
const appIds = await provisionApps(cookieString, csrfToken, primaryWsId, secondaryWsId)
console.warn(`[provision] Provisioned ${Object.keys(appIds).length} apps`)
// 4b. Switch back to primaryWsId so the session ends in the correct workspace.
// provisionApps processes ws2-workflow.yml last (EE mode), leaving the server
// session in secondaryWsId. Suite jobs that share this token would then have
// their describe calls rejected with "workspace_id does not match app's workspace".
await fetch(`${base}/console/api/workspaces/switch`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Cookie: cookieString,
'X-CSRF-Token': csrfToken,
},
body: JSON.stringify({ tenant_id: primaryWsId }),
signal: AbortSignal.timeout(10_000),
}).catch((err: unknown) =>
console.warn(`[provision] switch-back to primary failed (non-fatal): ${err}`),
)
console.warn(`[provision] Session workspace reset to primary: ${primaryWsId}`)
// 5. Write outputs
await writeOutputs({
DIFY_E2E_TOKEN: primaryToken,
DIFY_E2E_WORKSPACE_ID: primaryWsId,
DIFY_E2E_WORKSPACE_NAME: primaryWsName,
DIFY_E2E_WS2_ID: secondaryWsId,
...appIds,
})
}
main().catch((err) => {
console.warn('[provision] Fatal:', err)
process.exit(1)
})
@@ -0,0 +1,266 @@
import type { CommandEntry } from './generate-command-tree.js'
import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { describe, expect, it } from 'vite-plus/test'
import {
buildTree,
discoverCommands,
formatModule,
generate,
pathToTokens,
tokensToIdentifier,
} from './generate-command-tree.js'
describe('pathToTokens', () => {
it('extracts tokens for nested command', () => {
expect(pathToTokens('src/commands/auth/devices/list/index.ts', 'src/commands')).toEqual([
'auth',
'devices',
'list',
])
})
it('extracts tokens for top-level command', () => {
expect(pathToTokens('src/commands/version/index.ts', 'src/commands')).toEqual(['version'])
})
it('normalizes backslashes (windows-style paths)', () => {
expect(pathToTokens('src\\commands\\auth\\login\\index.ts', 'src/commands')).toEqual([
'auth',
'login',
])
})
})
describe('tokensToIdentifier', () => {
it('pascal-cases joined tokens', () => {
expect(tokensToIdentifier(['auth', 'devices', 'list'])).toBe('AuthDevicesList')
expect(tokensToIdentifier(['version'])).toBe('Version')
expect(tokensToIdentifier(['run', 'app', 'resume'])).toBe('RunAppResume')
})
it('splits hyphenated tokens', () => {
expect(tokensToIdentifier(['agent-chat'])).toBe('AgentChat')
expect(tokensToIdentifier(['my-cmd', 'sub-thing'])).toBe('MyCmdSubThing')
})
it('prefixes underscore on reserved words', () => {
expect(tokensToIdentifier(['delete'])).toBe('_Delete')
})
})
describe('buildTree', () => {
it('assembles a nested tree from entries', () => {
const entries = [
{
tokens: ['auth', 'login'],
identifier: 'AuthLogin',
importPath: '@/commands/auth/login/index',
},
{
tokens: ['auth', 'devices', 'list'],
identifier: 'AuthDevicesList',
importPath: '@/commands/auth/devices/list/index',
},
{ tokens: ['version'], identifier: 'Version', importPath: '@/commands/version/index' },
]
const tree = buildTree(entries)
expect(tree.subcommands.get('auth')?.command).toBeUndefined()
expect(tree.subcommands.get('auth')?.subcommands.get('login')?.command).toBe('AuthLogin')
expect(
tree.subcommands.get('auth')?.subcommands.get('devices')?.subcommands.get('list')?.command,
).toBe('AuthDevicesList')
expect(tree.subcommands.get('version')?.command).toBe('Version')
})
it('supports a parent command with its own children', () => {
const entries = [
{ tokens: ['run', 'app'], identifier: 'RunApp', importPath: '@/commands/run/app/index' },
{
tokens: ['run', 'app', 'resume'],
identifier: 'RunAppResume',
importPath: '@/commands/run/app/resume/index',
},
]
const tree = buildTree(entries)
const runApp = tree.subcommands.get('run')?.subcommands.get('app')
expect(runApp?.command).toBe('RunApp')
expect(runApp?.subcommands.get('resume')?.command).toBe('RunAppResume')
})
})
describe('formatModule', () => {
it('produces a deterministic ESM file with imports + tree literal', () => {
const entries: CommandEntry[] = [
{
tokens: ['auth', 'login'],
identifier: 'AuthLogin',
importPath: '@/commands/auth/login/index',
},
{ tokens: ['version'], identifier: 'Version', importPath: '@/commands/version/index' },
{
tokens: ['auth', 'devices', 'list'],
identifier: 'AuthDevicesList',
importPath: '@/commands/auth/devices/list/index',
},
]
const tree = buildTree(entries)
const out = formatModule(entries, tree)
expect(out).toBe(
`// @generated by scripts/generate-command-tree.ts — DO NOT EDIT.
// Regenerate via \`pnpm tree:gen\`. Drift gated by \`pnpm tree:check\` in CI.
import type { CommandTree } from '@/plugins/commands/registry'
import AuthDevicesList from '@/commands/auth/devices/list/index'
import AuthLogin from '@/commands/auth/login/index'
import Version from '@/commands/version/index'
export const commandTree: CommandTree = {
auth: {
subcommands: {
devices: {
subcommands: {
list: { command: AuthDevicesList, subcommands: {} },
},
},
login: { command: AuthLogin, subcommands: {} },
},
},
version: { command: Version, subcommands: {} },
}
`,
)
})
it('emits parent-with-own-command shape', () => {
const entries: CommandEntry[] = [
{ tokens: ['run', 'app'], identifier: 'RunApp', importPath: '@/commands/run/app/index' },
{
tokens: ['run', 'app', 'resume'],
identifier: 'RunAppResume',
importPath: '@/commands/run/app/resume/index',
},
]
const tree = buildTree(entries)
const out = formatModule(entries, tree)
expect(out).toContain(`run: {
subcommands: {
app: {
command: RunApp,
subcommands: {
resume: { command: RunAppResume, subcommands: {} },
},
},
},
},`)
})
it('imports sorted alphabetically by import path', () => {
const entries: CommandEntry[] = [
{ tokens: ['version'], identifier: 'Version', importPath: '@/commands/version/index' },
{
tokens: ['auth', 'login'],
identifier: 'AuthLogin',
importPath: '@/commands/auth/login/index',
},
]
const out = formatModule(entries, buildTree(entries))
const authIdx = out.indexOf('AuthLogin')
const verIdx = out.indexOf('Version')
expect(authIdx).toBeLessThan(verIdx)
})
it('quotes hyphenated keys and leaves plain identifier keys unquoted', () => {
const entries: CommandEntry[] = [
{
tokens: ['export', 'app'],
identifier: 'ExportApp',
importPath: '@/commands/export/app/index',
},
{
tokens: ['export', 'studio-app'],
identifier: 'ExportStudioApp',
importPath: '@/commands/export/studio-app/index',
},
]
const out = formatModule(entries, buildTree(entries))
expect(out).toContain(`'studio-app': { command: ExportStudioApp, subcommands: {} },`)
expect(out).toContain(`app: { command: ExportApp, subcommands: {} },`)
expect(out).not.toContain(`'app':`)
})
})
function makeFixture(): string {
const root = mkdtempSync(join(tmpdir(), 'difyctl-codegen-'))
const commands = join(root, 'src', 'commands')
mkdirSync(join(commands, 'auth', 'login'), { recursive: true })
writeFileSync(join(commands, 'auth', 'login', 'index.ts'), 'export default class Login {}\n')
mkdirSync(join(commands, 'auth', 'devices', 'list'), { recursive: true })
writeFileSync(
join(commands, 'auth', 'devices', 'list', 'index.ts'),
'export default class DevicesList {}\n',
)
mkdirSync(join(commands, '_shared'), { recursive: true })
writeFileSync(join(commands, '_shared', 'index.ts'), 'export default class Shared {}\n')
mkdirSync(join(commands, 'version'), { recursive: true })
writeFileSync(join(commands, 'version', 'index.ts'), 'export default class Version {}\n')
return root
}
describe('discoverCommands', () => {
it('returns sorted entries, skipping _-prefixed segments', async () => {
const root = makeFixture()
const entries = await discoverCommands(join(root, 'src', 'commands'))
expect(entries.map((e) => e.tokens.join('/'))).toEqual([
'auth/devices/list',
'auth/login',
'version',
])
expect(entries.find((e) => e.tokens[0] === '_shared')).toBeUndefined()
})
it('errors on a loose .ts file under commands/', async () => {
const root = mkdtempSync(join(tmpdir(), 'difyctl-codegen-loose-'))
const commands = join(root, 'src', 'commands')
mkdirSync(commands, { recursive: true })
writeFileSync(join(commands, 'foo.ts'), 'export default class Foo {}\n')
await expect(discoverCommands(commands)).rejects.toThrow(/must live under their own folder/)
})
})
describe('generate', () => {
it('writes tree.generated.ts on default mode', async () => {
const root = makeFixture()
const commandsDir = join(root, 'src', 'commands')
const result = await generate({ commandsDir, mode: 'write' })
expect(result.mode).toBe('write')
const target = join(commandsDir, 'tree.generated.ts')
expect(existsSync(target)).toBe(true)
const content = readFileSync(target, 'utf8')
expect(content).toContain('@generated')
expect(content).toContain('import AuthLogin')
expect(content).toContain('import AuthDevicesList')
expect(content).toContain('import Version')
})
it('returns ok: true on --check when file matches', async () => {
const root = makeFixture()
const commandsDir = join(root, 'src', 'commands')
await generate({ commandsDir, mode: 'write' })
const result = await generate({ commandsDir, mode: 'check' })
if (result.mode !== 'check') throw new Error('expected check mode')
expect(result.ok).toBe(true)
})
it('returns ok: false on --check when file is stale', async () => {
const root = makeFixture()
const commandsDir = join(root, 'src', 'commands')
await generate({ commandsDir, mode: 'write' })
writeFileSync(join(commandsDir, 'tree.generated.ts'), '// stale\n')
const result = await generate({ commandsDir, mode: 'check' })
if (result.mode !== 'check') throw new Error('expected check mode')
expect(result.ok).toBe(false)
if (!result.ok) expect(result.diff).toBeDefined()
})
})
@@ -0,0 +1,309 @@
import { readdir, readFile, rename, writeFile } from 'node:fs/promises'
import { join, relative, sep } from 'node:path'
import { fileURLToPath } from 'node:url'
import { isExcludedCommandPath } from '../src/plugins/commands/command-fs.js'
const RESERVED_JS_KEYWORDS = new Set([
'break',
'case',
'catch',
'class',
'const',
'continue',
'debugger',
'default',
'delete',
'do',
'else',
'enum',
'export',
'extends',
'false',
'finally',
'for',
'function',
'if',
'import',
'in',
'instanceof',
'new',
'null',
'return',
'super',
'switch',
'this',
'throw',
'true',
'try',
'typeof',
'var',
'void',
'while',
'with',
'yield',
])
export type CommandEntry = {
readonly tokens: readonly string[]
readonly identifier: string
readonly importPath: string
}
export type TreeNode = {
command?: string
subcommands: Map<string, TreeNode>
}
export function pathToTokens(filePath: string, commandsRoot: string): string[] {
const normalized = filePath.replace(/\\/g, '/')
const root = commandsRoot.replace(/\\/g, '/').replace(/\/$/, '')
const trimmed = normalized.startsWith(`${root}/`) ? normalized.slice(root.length + 1) : normalized
const withoutIndex = trimmed.replace(/\/index\.ts$/, '')
return withoutIndex.split('/').filter((s) => s.length > 0)
}
function capitalize(part: string): string {
if (part.length === 0) return ''
return part[0]!.toUpperCase() + part.slice(1)
}
export function tokensToIdentifier(tokens: readonly string[]): string {
const id = tokens
.flatMap((t) => t.split(/[-_]/))
.map(capitalize)
.join('')
if (RESERVED_JS_KEYWORDS.has(id.toLowerCase())) return `_${id}`
return id
}
export function buildTree(entries: readonly CommandEntry[]): TreeNode {
const root: TreeNode = { subcommands: new Map() }
for (const entry of entries) {
let node = root
for (let i = 0; i < entry.tokens.length; i++) {
const tok = entry.tokens[i]!
let next = node.subcommands.get(tok)
if (!next) {
next = { subcommands: new Map() }
node.subcommands.set(tok, next)
}
node = next
}
node.command = entry.identifier
}
return root
}
const HEADER = `// @generated by scripts/generate-command-tree.ts — DO NOT EDIT.
// Regenerate via \`pnpm tree:gen\`. Drift gated by \`pnpm tree:check\` in CI.
`
function compareStrings(a: string, b: string): number {
if (a < b) return -1
if (a > b) return 1
return 0
}
function emitImports(entries: readonly CommandEntry[]): string {
const sorted = [...entries].sort((a, b) => compareStrings(a.importPath, b.importPath))
const lines = [`import type { CommandTree } from '@/plugins/commands/registry'`]
for (const e of sorted) lines.push(`import ${e.identifier} from '${e.importPath}'`)
return lines.join('\n')
}
function emitNode(node: TreeNode, indent: string): string {
const inner = `${indent} `
const keys = [...node.subcommands.keys()].sort()
const parts: string[] = []
if (node.command !== undefined) parts.push(`${inner}command: ${node.command},`)
if (keys.length === 0) {
parts.push(`${inner}subcommands: {},`)
} else {
parts.push(`${inner}subcommands: {`)
for (const key of keys) {
const child = node.subcommands.get(key)!
parts.push(emitEntry(key, child, `${inner} `))
}
parts.push(`${inner}},`)
}
return parts.join('\n')
}
function needsQuoting(key: string): boolean {
// A bare object key must be a valid JS identifier: the start class excludes digits
// (letter/_/$ only), so a leading digit fails the match and the key gets quoted.
return !/^[A-Z_$][\w$]*$/i.test(key)
}
function emitKey(key: string): string {
return needsQuoting(key) ? `'${key}'` : key
}
function emitEntry(key: string, node: TreeNode, indent: string): string {
const k = emitKey(key)
const isLeaf = node.subcommands.size === 0 && node.command !== undefined
if (isLeaf) return `${indent}${k}: { command: ${node.command}, subcommands: {} },`
return [`${indent}${k}: {`, emitNode(node, indent), `${indent}},`].join('\n')
}
export function formatModule(entries: readonly CommandEntry[], tree: TreeNode): string {
const importsBlock = emitImports(entries)
const topKeys = [...tree.subcommands.keys()].sort()
// Empty object on one line, matching the repo formatter's own convention —
// otherwise a fresh `tree:gen` and `tree:check` disagree right after a commit.
const literal =
topKeys.length === 0
? 'export const commandTree: CommandTree = {}'
: [
'export const commandTree: CommandTree = {',
...topKeys.map((key) => emitEntry(key, tree.subcommands.get(key)!, ' ')),
'}',
].join('\n')
return `${HEADER}\n${importsBlock}\n\n${literal}\n`
}
async function walk(dir: string): Promise<string[]> {
const out: string[] = []
const entries = await readdir(dir, { withFileTypes: true })
for (const e of entries) {
const full = join(dir, e.name)
if (e.isDirectory()) out.push(...(await walk(full)))
else if (e.isFile()) out.push(full)
}
return out
}
function toPosix(p: string): string {
return p.split(sep).join('/')
}
export async function discoverCommands(commandsDir: string): Promise<CommandEntry[]> {
const all = await walk(commandsDir)
const tsFiles = all.filter(
(f) => f.endsWith('.ts') && !f.endsWith('.test.ts') && !f.endsWith('.d.ts'),
)
const loose: string[] = []
for (const abs of tsFiles) {
const rel = toPosix(relative(commandsDir, abs))
if (isExcludedCommandPath(rel)) continue
if (rel === 'tree.ts' || rel === 'tree.generated.ts') continue
// Only flag files directly under commands/ (no path separator — no parent folder)
if (!rel.includes('/')) loose.push(rel)
}
if (loose.length > 0) {
const list = loose.map((p) => ` - src/commands/${p}`).join('\n')
throw new Error(
`commands must live under their own folder (see CLAUDE memory: feedback_cli_command_structure). Found:\n${list}`,
)
}
const entries: CommandEntry[] = []
for (const abs of tsFiles) {
const rel = toPosix(relative(commandsDir, abs))
if (isExcludedCommandPath(rel)) continue
if (!rel.endsWith('/index.ts')) continue
const tokens = pathToTokens(rel, '')
if (tokens.length === 0) continue
if (tokens[0]!.startsWith('-')) throw new Error(`command token cannot start with '-': ${rel}`)
entries.push({
tokens,
identifier: tokensToIdentifier(tokens),
importPath: `@/commands/${tokens.join('/')}/index`,
})
}
entries.sort((a, b) => compareStrings(a.importPath, b.importPath))
if (entries.length === 0)
throw new Error(`no commands found under ${commandsDir} — expected <verb>/index.ts folders`)
assertUniqueIdentifiers(entries)
return entries
}
function assertUniqueIdentifiers(entries: readonly CommandEntry[]): void {
const seen = new Map<string, string>()
for (const e of entries) {
const prev = seen.get(e.identifier)
if (prev !== undefined)
throw new Error(`identifier collision: ${e.identifier} from ${prev} and ${e.importPath}`)
seen.set(e.identifier, e.importPath)
}
}
export type GenerateOptions = {
readonly commandsDir: string
readonly mode: 'write' | 'check'
}
export type GenerateResult =
| { mode: 'write'; wrote: boolean; path: string }
| { mode: 'check'; ok: true; path: string }
| { mode: 'check'; ok: false; path: string; diff: string }
export async function generate(opts: GenerateOptions): Promise<GenerateResult> {
const entries = await discoverCommands(opts.commandsDir)
const tree = buildTree(entries)
const content = formatModule(entries, tree)
const target = join(opts.commandsDir, 'tree.generated.ts')
if (opts.mode === 'check') {
let onDisk = ''
try {
onDisk = await readFile(target, 'utf8')
} catch {
onDisk = ''
}
if (onDisk === content) return { mode: 'check', ok: true, path: target }
return { mode: 'check', ok: false, path: target, diff: shortDiff(onDisk, content) }
}
const tmp = `${target}.tmp-${process.pid}-${Date.now()}`
await writeFile(tmp, content, 'utf8')
await rename(tmp, target)
return { mode: 'write', wrote: true, path: target }
}
function shortDiff(a: string, b: string): string {
const aLines = a.split('\n')
const bLines = b.split('\n')
const lines: string[] = []
const max = Math.max(aLines.length, bLines.length)
for (let i = 0; i < max; i++) {
if (aLines[i] !== bLines[i]) {
if (aLines[i] !== undefined) lines.push(`- ${aLines[i]}`)
if (bLines[i] !== undefined) lines.push(`+ ${bLines[i]}`)
}
}
return lines.slice(0, 40).join('\n')
}
async function main(): Promise<void> {
const here = fileURLToPath(import.meta.url)
const commandsDir = join(here, '..', '..', 'src', 'commands')
const checkMode = process.argv.includes('--check')
const result = await generate({ commandsDir, mode: checkMode ? 'check' : 'write' })
if (result.mode === 'write') {
process.stderr.write(`tree:gen wrote ${result.path}\n`)
return
}
if (result.ok) {
process.stderr.write(`tree:check ok\n`)
return
}
process.stderr.write(
`tree:check FAILED — tree.generated.ts is stale.\nDiff (first 40 lines):\n${result.diff}\n\nRun \`pnpm tree:gen\` and commit.\n`,
)
process.exit(1)
}
const invokedDirectly =
process.argv[1] !== undefined && fileURLToPath(import.meta.url) === process.argv[1]
if (invokedDirectly) await main()
+264
View File
@@ -0,0 +1,264 @@
#!/bin/sh
# install-cli.sh — one-line difyctl installer. difyctl ships as assets on Dify
# GitHub Releases; this installs the build matching your Dify version.
#
# usage:
# curl -fsSL https://raw.githubusercontent.com/langgenius/dify/main/cli/scripts/install-cli.sh | sh
#
# env:
# DIFY_VERSION Dify release tag to install difyctl from (e.g. 1.14.2). Primary key.
# DIFYCTL_VERSION difyctl version pin (used only when DIFY_VERSION is unset).
# DIFYCTL_PREFIX install prefix (default $HOME/.local); binary -> $PREFIX/bin/difyctl
# DIFYCTL_INSTALL_DIR the bin folder itself (wins over DIFYCTL_PREFIX); binary -> $DIR/difyctl
# DIFYCTL_REPO release source repo (default langgenius/dify)
# GITHUB_TOKEN GitHub token (or GH_TOKEN) to raise the API rate limit to 5000/hour.
# requires: curl, uname, sort -V, and sha256sum or shasum.
set -eu
REPO="${DIFYCTL_REPO:-langgenius/dify}"
DIFY_VERSION="${DIFY_VERSION:-}"
DIFYCTL_VERSION="${DIFYCTL_VERSION:-}"
GH_AUTH="${GITHUB_TOKEN:-${GH_TOKEN:-}}"
# fetch_json runs in a subshell, so it reports failures via this file, not a variable.
FETCH_ERR_FILE="${TMPDIR:-/tmp}/difyctl-fetcherr.$$"
API="https://api.github.com/repos/${REPO}"
DL="https://github.com/${REPO}/releases/download"
err() { printf '%s\n' "install-cli: $*" >&2; }
die() { err "$*"; rm -f "$FETCH_ERR_FILE"; exit 1; }
need() { command -v "$1" >/dev/null 2>&1 || die "$1 is required"; }
re_escape() { printf '%s' "$1" | sed 's/[][\\.^$*+?(){}|/]/\\&/g'; }
# print_skill_hint BIN: the hint names a v2 command, so a binary without it (any v1 build) gets none.
print_skill_hint() {
"$1" install skills --help >/dev/null 2>&1 || return 0
printf '%s\n' 'AI agents: run `difyctl install skills <skills root>` after each install or upgrade; the skill ships inside the binary.'
}
# DIFYCTL_INSTALL_DIR names the bin folder itself; DIFYCTL_PREFIX the folder above it.
bin_dir_for() {
printf '%s' "${DIFYCTL_INSTALL_DIR:-${DIFYCTL_PREFIX:-${HOME}/.local}/bin}"
}
# install_binary SRC DEST: stage the copy next to DEST, then rename it over DEST, so a
# running difyctl keeps its old file and DEST is never half written.
install_binary() {
_stage="$(dirname "$2")/.difyctl.install.$$"
if cp "$1" "$_stage" && chmod 0755 "$_stage" && mv -f "$_stage" "$2"; then
return 0
fi
rm -f "$_stage"
die "cannot write $2"
}
detect_target() {
case "$(uname -s)" in
Linux*) _os=linux ;;
Darwin*) _os=darwin ;;
*) die "unsupported OS: $(uname -s) (use install.ps1 on Windows)" ;;
esac
case "$(uname -m)" in
x86_64|amd64) _arch=x64 ;;
arm64|aarch64) _arch=arm64 ;;
*) die "unsupported arch: $(uname -m)" ;;
esac
printf '%s-%s' "$_os" "$_arch"
}
# list_asset_names (reads release JSON on stdin) -> one difyctl asset name per line
list_asset_names() {
grep -oE '"name"[[:space:]]*:[[:space:]]*"difyctl-v[^"]*"' \
| sed -E 's#.*"name"[[:space:]]*:[[:space:]]*"([^"]*)".*#\1#'
}
# pick_asset TARGET (reads release JSON on stdin) -> highest-semver matching asset name
pick_asset() {
_target=$(re_escape "$1")
list_asset_names \
| grep -E -- "-${_target}(\\.exe)?\$" \
| grep -vE -- '-checksums\.txt$' \
| sort -V | tail -1
}
# asset_version ASSET_NAME TARGET -> difyctl version embedded in the name
asset_version() {
_target=$(re_escape "$2")
printf '%s' "$1" | sed -E "s#^difyctl-v(.*)-${_target}(\\.exe)?\$#\\1#"
}
# list_release_tags (reads /releases array JSON on stdin) -> tag per line, newest first
list_release_tags() {
grep -oE '"tag_name"[[:space:]]*:[[:space:]]*"[^"]*"' \
| sed -E 's#.*:[[:space:]]*"([^"]*)".*#\1#'
}
# fetch_json URL -> body on stdout, 0 on success. On failure writes the cause to
# FETCH_ERR_FILE (ratelimit:<epoch> | http:<code> | network) and returns nonzero.
# Inspects the status and rate-limit headers, so it must not use curl -f.
fetch_json() {
rm -f "$FETCH_ERR_FILE"
_hdr=$(mktemp) || return 1
_body=$(mktemp) || { rm -f "$_hdr"; return 1; }
if [ -n "$GH_AUTH" ]; then
_code=$(curl -sSL -D "$_hdr" -o "$_body" -w '%{http_code}' \
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer ${GH_AUTH}" \
"$1" 2>/dev/null) || _code=000
else
_code=$(curl -sSL -D "$_hdr" -o "$_body" -w '%{http_code}' \
-H "Accept: application/vnd.github+json" \
"$1" 2>/dev/null) || _code=000
fi
case "$_code" in
2*) cat "$_body"; rm -f "$_hdr" "$_body"; return 0 ;;
403|429)
_rem=$(awk 'tolower($1)=="x-ratelimit-remaining:"{gsub(/\r/,"",$2);v=$2} END{print v}' "$_hdr")
if [ "$_code" = "429" ] || [ "${_rem:-}" = "0" ]; then
_rst=$(awk 'tolower($1)=="x-ratelimit-reset:"{gsub(/\r/,"",$2);v=$2} END{print v}' "$_hdr")
printf 'ratelimit:%s' "$_rst" > "$FETCH_ERR_FILE"
else
printf 'http:%s' "$_code" > "$FETCH_ERR_FILE"
fi ;;
000) printf 'network' > "$FETCH_ERR_FILE" ;;
*) printf 'http:%s' "$_code" > "$FETCH_ERR_FILE" ;;
esac
rm -f "$_hdr" "$_body"
return 1
}
# rate_limit_hint [RESET_EPOCH] -> explain the GitHub API limit and how to proceed.
rate_limit_hint() {
err "GitHub API rate limit exceeded (unauthenticated requests are capped at 60/hour per IP)."
case "${1:-}" in
'' | *[!0-9]*) ;;
*)
_now=$(date +%s 2>/dev/null) || _now=""
if [ -n "$_now" ]; then
_mins=$(( ($1 - _now + 59) / 60 ))
if [ "$_mins" -gt 0 ]; then
err "The limit resets in ~${_mins} min."
fi
fi ;;
esac
err "To proceed now, authenticate to raise the limit to 5000/hour:"
err " curl -fsSL <install-url> | GITHUB_TOKEN=<token> sh"
err "Tip: pinning DIFY_VERSION makes a single API call (DIFYCTL_VERSION scans many)."
}
# True if the last fetch_json hit a rate limit — lets a subshell bail without printing.
fetch_hit_ratelimit() {
[ -f "$FETCH_ERR_FILE" ] || return 1
case "$(cat "$FETCH_ERR_FILE" 2>/dev/null || true)" in
ratelimit:*) return 0 ;;
esac
return 1
}
# Explain and exit if the last fetch_json hit a rate limit; else return. Main shell only.
maybe_ratelimit_exit() {
fetch_hit_ratelimit || return 0
_reset=$(cat "$FETCH_ERR_FILE" 2>/dev/null || true)
rm -f "$FETCH_ERR_FILE"
rate_limit_hint "${_reset#ratelimit:}"
exit 1
}
# find_release_for_difyctl WANT TARGET -> newest Dify tag whose assets host that difyctl build
find_release_for_difyctl() {
_want="$1"
_target="$2"
_raw=$(fetch_json "${API}/releases?per_page=100") \
|| { fetch_hit_ratelimit && return 1; die "failed to query ${REPO} releases (network error or GitHub API rate limit)"; }
_tags=$(printf '%s' "$_raw" | list_release_tags)
for _t in $_tags; do
_rel=$(fetch_json "${API}/releases/tags/${_t}") \
|| { fetch_hit_ratelimit && return 1; err "fetch failed for ${_t}, skipping"; continue; }
_name=$(printf '%s' "$_rel" | pick_asset "$_target")
[ -n "$_name" ] || continue
if [ "$(asset_version "$_name" "$_target")" = "$_want" ]; then
printf '%s' "$_t"
return 0
fi
done
return 1
}
resolve_release() {
_target="$1"
if [ -n "$DIFY_VERSION" ]; then
REL=$(fetch_json "${API}/releases/tags/${DIFY_VERSION}") \
|| { maybe_ratelimit_exit; die "Dify release ${DIFY_VERSION} not found"; }
DIFY_TAG="$DIFY_VERSION"
elif [ -n "$DIFYCTL_VERSION" ]; then
DIFY_TAG=$(find_release_for_difyctl "$DIFYCTL_VERSION" "$_target") \
|| { maybe_ratelimit_exit; die "difyctl ${DIFYCTL_VERSION} not found on any Dify release"; }
REL=$(fetch_json "${API}/releases/tags/${DIFY_TAG}") \
|| { maybe_ratelimit_exit; die "failed to fetch Dify release ${DIFY_TAG}"; }
else
REL=$(fetch_json "${API}/releases/latest") \
|| { maybe_ratelimit_exit; die "failed to query latest Dify release (set DIFY_VERSION to pin one)"; }
DIFY_TAG=$(printf '%s' "$REL" | list_release_tags | head -1)
[ -n "$DIFY_TAG" ] || die "could not parse a tag from the latest Dify release"
fi
}
main() {
trap 'rm -f "$FETCH_ERR_FILE"' EXIT INT TERM
need curl
need uname
sort -V /dev/null >/dev/null 2>&1 || die "sort with -V support is required (install coreutils)"
if command -v sha256sum >/dev/null 2>&1; then
HASH="sha256sum"
elif command -v shasum >/dev/null 2>&1; then
HASH="shasum -a 256"
else
die "need sha256sum or shasum"
fi
target=$(detect_target)
resolve_release "$target"
asset=$(printf '%s' "$REL" | pick_asset "$target")
[ -n "$asset" ] || die "no difyctl published for Dify ${DIFY_TAG} (target ${target}); set DIFY_VERSION to a release that has one"
version=$(asset_version "$asset" "$target")
checksums="difyctl-v${version}-checksums.txt"
base="${DL}/${DIFY_TAG}"
tmp=$(mktemp -d 2>/dev/null || mktemp -d -t difyctl-install)
trap 'rm -rf "$tmp"; rm -f "$FETCH_ERR_FILE"' EXIT INT TERM
printf 'downloading %s (Dify %s)...\n' "$asset" "$DIFY_TAG"
curl -fsSL "${base}/${asset}" -o "${tmp}/${asset}" \
|| die "download failed: ${base}/${asset}"
curl -fsSL "${base}/${checksums}" -o "${tmp}/${checksums}" \
|| die "checksum manifest download failed: ${base}/${checksums}"
_pattern=$(re_escape "$asset")
_sumline=$(grep -E -- "[[:space:]]${_pattern}\$" "${tmp}/${checksums}") || true
[ -n "$_sumline" ] || die "no checksum entry for ${asset}"
(
cd "$tmp"
printf '%s\n' "$_sumline" | $HASH -c -
) || die "checksum mismatch for ${asset}"
bin_dir=$(bin_dir_for)
mkdir -p "$bin_dir"
target_bin="${bin_dir}/difyctl"
install_binary "${tmp}/${asset}" "$target_bin"
printf '\ndifyctl v%s installed (from Dify %s): %s\n' "$version" "$DIFY_TAG" "$target_bin"
case ":${PATH}:" in
*":${bin_dir}:"*)
printf 'verify: run "difyctl version"\n'
print_skill_hint "$target_bin"
;;
*)
printf '\n%s is not on your PATH. Add this to your shell profile:\n' "$bin_dir"
printf ' export PATH="%s:$PATH"\n' "$bin_dir"
;;
esac
}
if [ "${DIFYCTL_INSTALL_LIB:-0}" != "1" ]; then
main "$@"
fi
@@ -0,0 +1,501 @@
import { execFileSync, spawnSync } from 'node:child_process'
import { chmodSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { describe, expect, it } from 'vite-plus/test'
const SCRIPT = fileURLToPath(new URL('./install-cli.sh', import.meta.url))
function pickAsset(target: string, releaseJson: string): string {
return execFileSync('sh', ['-c', `. "${SCRIPT}"; pick_asset "$1"`, 'sh', target], {
input: releaseJson,
encoding: 'utf8',
env: { ...process.env, DIFYCTL_INSTALL_LIB: '1' },
}).trim()
}
function assetVersion(name: string, target: string): string {
return execFileSync('sh', ['-c', `. "${SCRIPT}"; asset_version "$1" "$2"`, 'sh', name, target], {
encoding: 'utf8',
env: { ...process.env, DIFYCTL_INSTALL_LIB: '1' },
}).trim()
}
// Stubs the only network primitive (fetch_json) so resolution logic runs fully
// offline. Routes by URL; release bodies come from env (TAG_<tag-with-._->_>),
// the latest release from LATEST_JSON, the listing from LIST_JSON. A missing
// fixture returns 22 to mimic `curl -f` on a 4xx.
/* oxlint-disable no-template-curly-in-string -- shell parameter expansions, not JS template literals */
const FETCH_STUB = [
'fetch_json() {',
' case "$1" in',
' *"/releases/latest") [ -n "${LATEST_JSON:-}" ] || return 22; printf "%s" "$LATEST_JSON" ;;',
' *"/releases?per_page=100") [ -n "${LIST_JSON:-}" ] || return 22; printf "%s" "$LIST_JSON" ;;',
' *"/releases/tags/"*)',
' _t=${1##*/releases/tags/};',
' _k=$(printf "TAG_%s" "$_t" | tr ".-" "__");',
' eval "_v=\\${$_k:-}";',
' [ -n "$_v" ] || return 22;',
' printf "%s" "$_v" ;;',
' *) return 22 ;;',
' esac',
'}',
].join('\n')
/* oxlint-enable no-template-curly-in-string */
function runLib(
program: string,
env: Record<string, string> = {},
): { code: number; stdout: string; stderr: string } {
const full = `. "${SCRIPT}"\n${FETCH_STUB}\n${program}`
const r = spawnSync('sh', ['-c', full], {
encoding: 'utf8',
env: {
...process.env,
DIFYCTL_INSTALL_LIB: '1',
DIFY_VERSION: '',
DIFYCTL_VERSION: '',
...env,
},
})
return { code: r.status ?? 1, stdout: (r.stdout ?? '').trim(), stderr: r.stderr ?? '' }
}
// Like runLib but with a caller-supplied fetch_json stub, so we can drive the
// real rate_limit_hint / maybe_ratelimit_exit / fetch_hit_ratelimit (which the
// script defines) by writing a classified reason to FETCH_ERR_FILE.
function runLibStub(
stub: string,
program: string,
env: Record<string, string> = {},
): { code: number; stderr: string } {
const full = `. "${SCRIPT}"\n${stub}\n${program}`
const r = spawnSync('sh', ['-c', full], {
encoding: 'utf8',
env: {
...process.env,
DIFYCTL_INSTALL_LIB: '1',
DIFY_VERSION: '',
DIFYCTL_VERSION: '',
...env,
},
})
return { code: r.status ?? 1, stderr: r.stderr ?? '' }
}
// A fetch_json that always fails with the given classification, mimicking the
// real one writing to FETCH_ERR_FILE from inside a command-substitution subshell.
function failStub(reason: string): string {
return `fetch_json() { printf '%s' '${reason}' > "$FETCH_ERR_FILE"; return 1; }`
}
const REL_1142 = JSON.stringify({
tag_name: '1.14.2',
assets: [{ name: 'difyctl-v0.2.0-linux-x64' }, { name: 'difyctl-v0.2.0-checksums.txt' }],
})
const REL_1150 = JSON.stringify({
tag_name: '1.15.0',
assets: [{ name: 'difyctl-v0.3.0-linux-x64' }],
})
const LIST_NEWEST_FIRST = JSON.stringify({
releases: [{ tag_name: '1.15.0' }, { tag_name: '1.14.2' }],
})
const RELEASE = JSON.stringify({
tag_name: '1.14.2',
name: 'Dify 1.14.2',
assets: [
{ name: 'difyctl-v0.1.0-rc.1-linux-x64' },
{ name: 'difyctl-v0.2.0-linux-x64' },
{ name: 'difyctl-v0.2.0-linux-arm64' },
{ name: 'difyctl-v0.2.0-darwin-arm64' },
{ name: 'difyctl-v0.2.0-windows-x64.exe' },
{ name: 'difyctl-v0.2.0-checksums.txt' },
{ name: 'some-other-asset.zip' },
],
})
describe('install-cli pick_asset', () => {
it('picks the highest difyctl version for a linux target', () => {
expect(pickAsset('linux-x64', RELEASE)).toBe('difyctl-v0.2.0-linux-x64')
})
it('matches the windows .exe asset', () => {
expect(pickAsset('windows-x64', RELEASE)).toBe('difyctl-v0.2.0-windows-x64.exe')
})
it('matches an arm64 target exactly (no x64 bleed-through)', () => {
expect(pickAsset('darwin-arm64', RELEASE)).toBe('difyctl-v0.2.0-darwin-arm64')
})
it('excludes the checksums asset', () => {
expect(pickAsset('linux-x64', RELEASE)).not.toContain('checksums')
})
it('yields empty when no asset matches the target', () => {
expect(pickAsset('darwin-x64', RELEASE)).toBe('')
})
it('picks the highest semver when several difyctl versions are present', () => {
const many = JSON.stringify({
assets: [
{ name: 'difyctl-v0.2.0-linux-x64' },
{ name: 'difyctl-v0.10.0-linux-x64' },
{ name: 'difyctl-v0.9.0-linux-x64' },
],
})
expect(pickAsset('linux-x64', many)).toBe('difyctl-v0.10.0-linux-x64')
})
})
describe('install-cli asset_version', () => {
it('extracts the version from a posix asset name', () => {
expect(assetVersion('difyctl-v0.2.0-linux-x64', 'linux-x64')).toBe('0.2.0')
})
it('extracts the version from a windows .exe asset name', () => {
expect(assetVersion('difyctl-v0.2.0-windows-x64.exe', 'windows-x64')).toBe('0.2.0')
})
it('extracts a prerelease version', () => {
expect(assetVersion('difyctl-v0.1.0-rc.1-linux-x64', 'linux-x64')).toBe('0.1.0-rc.1')
})
})
describe('install-cli resolve_release', () => {
it('DIFY_VERSION pins the release directly', () => {
const r = runLib('resolve_release linux-x64; printf "%s" "$DIFY_TAG"', {
DIFY_VERSION: '1.14.2',
TAG_1_14_2: REL_1142,
})
expect(r.code).toBe(0)
expect(r.stdout).toBe('1.14.2')
})
it('DIFY_VERSION that does not exist dies with a clear message', () => {
const r = runLib('resolve_release linux-x64', { DIFY_VERSION: '9.9.9' })
expect(r.code).not.toBe(0)
expect(r.stderr).toContain('Dify release 9.9.9 not found')
})
it('blank resolves to the latest stable release', () => {
const r = runLib('resolve_release linux-x64; printf "%s" "$DIFY_TAG"', {
LATEST_JSON: REL_1150,
})
expect(r.code).toBe(0)
expect(r.stdout).toBe('1.15.0')
})
it('blank dies when the latest query fails (no silent fallback)', () => {
const r = runLib('resolve_release linux-x64')
expect(r.code).not.toBe(0)
expect(r.stderr).toContain('failed to query latest Dify release')
})
it('DIFYCTL_VERSION resolves to the release hosting that build', () => {
const r = runLib('resolve_release linux-x64; printf "%s" "$DIFY_TAG"', {
DIFYCTL_VERSION: '0.2.0',
LIST_JSON: LIST_NEWEST_FIRST,
TAG_1_15_0: REL_1150,
TAG_1_14_2: REL_1142,
})
expect(r.code).toBe(0)
expect(r.stdout).toBe('1.14.2')
})
it('DIFYCTL_VERSION not hosted anywhere dies', () => {
const r = runLib('resolve_release linux-x64', {
DIFYCTL_VERSION: '9.9.9',
LIST_JSON: LIST_NEWEST_FIRST,
TAG_1_15_0: REL_1150,
TAG_1_14_2: REL_1142,
})
expect(r.code).not.toBe(0)
expect(r.stderr).toContain('difyctl 9.9.9 not found on any Dify release')
})
})
describe('install-cli find_release_for_difyctl', () => {
it('returns the newest release whose assets host the wanted build', () => {
const r = runLib('find_release_for_difyctl 0.2.0 linux-x64', {
LIST_JSON: LIST_NEWEST_FIRST,
TAG_1_15_0: REL_1150,
TAG_1_14_2: REL_1142,
})
expect(r.code).toBe(0)
expect(r.stdout).toBe('1.14.2')
})
it('dies (not false-negative) when the releases listing fails', () => {
const r = runLib('find_release_for_difyctl 0.2.0 linux-x64')
expect(r.code).not.toBe(0)
expect(r.stderr).toContain('failed to query')
})
it('warns and skips a release whose fetch fails, then finds it later', () => {
const r = runLib('find_release_for_difyctl 0.2.0 linux-x64', {
LIST_JSON: LIST_NEWEST_FIRST,
TAG_1_14_2: REL_1142,
})
expect(r.code).toBe(0)
expect(r.stdout).toBe('1.14.2')
expect(r.stderr).toContain('fetch failed for 1.15.0')
})
})
describe('install-cli rate limit', () => {
const futureReset = String(Math.floor(Date.now() / 1000) + 1800)
it('latest: reports the rate limit with reset ETA and remediation, not a generic error', () => {
const r = runLibStub(failStub(`ratelimit:${futureReset}`), 'resolve_release linux-x64')
expect(r.code).not.toBe(0)
expect(r.stderr).toContain('rate limit exceeded')
expect(r.stderr).toContain('resets in ~')
expect(r.stderr).toContain('GITHUB_TOKEN')
expect(r.stderr).not.toContain('failed to query latest')
})
it('DIFY_VERSION: rate limit wins over the misleading "not found" message', () => {
const r = runLibStub(failStub(`ratelimit:${futureReset}`), 'resolve_release linux-x64', {
DIFY_VERSION: '1.15.0',
})
expect(r.code).not.toBe(0)
expect(r.stderr).toContain('rate limit exceeded')
expect(r.stderr).not.toContain('not found')
})
it('DIFYCTL_VERSION: rate limit surfaces from the nested subshell, not "not found"', () => {
const r = runLibStub(failStub(`ratelimit:${futureReset}`), 'resolve_release linux-x64', {
DIFYCTL_VERSION: '0.2.0',
})
expect(r.code).not.toBe(0)
expect(r.stderr).toContain('rate limit exceeded')
expect(r.stderr).not.toContain('not found')
})
it('omits the ETA line when the reset epoch is missing', () => {
const r = runLibStub(failStub('ratelimit:'), 'resolve_release linux-x64')
expect(r.code).not.toBe(0)
expect(r.stderr).toContain('rate limit exceeded')
expect(r.stderr).not.toContain('resets in ~')
})
it('a non-rate-limit HTTP error falls back to the generic message (no false hint)', () => {
const r = runLibStub(failStub('http:500'), 'resolve_release linux-x64')
expect(r.code).not.toBe(0)
expect(r.stderr).toContain('failed to query latest')
expect(r.stderr).not.toContain('rate limit exceeded')
})
})
// A stand-in for curl that honours the flags fetch_json passes (-D/-o/-w/-H) and
// fabricates a response per FAKE_MODE, so the tests exercise the REAL fetch_json
// (its curl invocation, header parsing, classification and token handling) rather
// than a stub. Header names it emits are lowercase, as HTTP/2 delivers them.
const FAKE_CURL = `#!/bin/sh
hdr=""; body=""
while [ $# -gt 0 ]; do
case "$1" in
-D) hdr="$2"; shift 2 ;;
-o) body="$2"; shift 2 ;;
-H) printf '%s\\n' "$2" >> "\${FAKE_HDR_LOG:-/dev/null}"; shift 2 ;;
-w) shift 2 ;;
*) shift ;;
esac
done
case "\${FAKE_MODE:-ok}" in
ok)
[ -n "$hdr" ] && printf 'HTTP/2 200\\r\\n\\r\\n' > "$hdr"
[ -n "$body" ] && printf '%s' "\${FAKE_BODY:-}" > "$body"
printf '200' ;;
ratelimit)
[ -n "$hdr" ] && printf 'HTTP/2 403\\r\\nx-ratelimit-remaining: 0\\r\\nx-ratelimit-reset: %s\\r\\n\\r\\n' "\${FAKE_RESET:-9999999999}" > "$hdr"
printf '403' ;;
perm403)
[ -n "$hdr" ] && printf 'HTTP/2 403\\r\\nx-ratelimit-remaining: 59\\r\\n\\r\\n' > "$hdr"
printf '403' ;;
notfound)
[ -n "$hdr" ] && printf 'HTTP/2 404\\r\\n\\r\\n' > "$hdr"
printf '404' ;;
net) exit 6 ;;
esac
`
// Drive the real fetch_json with FAKE_CURL first on PATH. Returns "OK|<body>" or
// "FAIL|<FETCH_ERR_FILE contents>", plus any -H lines the fake curl received.
function runRealFetch(
mode: string,
env: Record<string, string> = {},
): { result: string; headers: string } {
const dir = mkdtempSync(join(tmpdir(), 'difyctl-fakecurl-'))
const hdrLog = join(dir, 'hdrlog')
writeFileSync(join(dir, 'curl'), FAKE_CURL)
chmodSync(join(dir, 'curl'), 0o755)
const program =
'if body=$(fetch_json "https://api.github.com/repos/x/releases/latest"); then printf \'OK|%s\' "$body"; else printf \'FAIL|%s\' "$(cat "$FETCH_ERR_FILE" 2>/dev/null)"; fi'
const r = spawnSync('sh', ['-c', `. "${SCRIPT}"\n${program}`], {
encoding: 'utf8',
env: {
...process.env,
PATH: `${dir}:${process.env.PATH ?? ''}`,
DIFYCTL_INSTALL_LIB: '1',
DIFY_VERSION: '',
DIFYCTL_VERSION: '',
FAKE_MODE: mode,
FAKE_HDR_LOG: hdrLog,
...env,
},
})
let headers = ''
try {
headers = readFileSync(hdrLog, 'utf8')
} catch {
/* no headers logged */
}
rmSync(dir, { recursive: true, force: true })
return { result: (r.stdout ?? '').trim(), headers }
}
describe('install-cli fetch_json (real, fake curl on PATH)', () => {
it('returns the response body on 200', () => {
expect(runRealFetch('ok', { FAKE_BODY: '{"tag_name":"1.15.0"}' }).result).toBe(
'OK|{"tag_name":"1.15.0"}',
)
})
it('classifies a 403 with x-ratelimit-remaining:0 as a rate limit and captures the reset', () => {
expect(runRealFetch('ratelimit', { FAKE_RESET: '1893456000' }).result).toBe(
'FAIL|ratelimit:1893456000',
)
})
it('classifies a 403 with tokens left as a plain http error, not a rate limit', () => {
expect(runRealFetch('perm403').result).toBe('FAIL|http:403')
})
it('classifies a 404 as an http error', () => {
expect(runRealFetch('notfound').result).toBe('FAIL|http:404')
})
it('classifies a curl transport failure as a network error', () => {
expect(runRealFetch('net').result).toBe('FAIL|network')
})
it('sends an Authorization bearer header when GITHUB_TOKEN is set', () => {
expect(runRealFetch('ok', { FAKE_BODY: '{}', GITHUB_TOKEN: 'ghp_secret' }).headers).toContain(
'Authorization: Bearer ghp_secret',
)
})
it('falls back to GH_TOKEN when GITHUB_TOKEN is unset', () => {
expect(
runRealFetch('ok', { FAKE_BODY: '{}', GITHUB_TOKEN: '', GH_TOKEN: 'gho_fallback' }).headers,
).toContain('Authorization: Bearer gho_fallback')
})
it('sends no Authorization header when neither token is set', () => {
expect(
runRealFetch('ok', { FAKE_BODY: '{}', GITHUB_TOKEN: '', GH_TOKEN: '' }).headers,
).not.toContain('Authorization')
})
})
describe('install-cli.sh install location', () => {
const where = (env: Record<string, string>) =>
runLib('bin_dir_for', { DIFYCTL_PREFIX: '', DIFYCTL_INSTALL_DIR: '', HOME: '/home/u', ...env })
.stdout
it('defaults to ~/.local/bin', () => {
expect(where({})).toBe('/home/u/.local/bin')
})
it('puts the binary under <DIFYCTL_PREFIX>/bin', () => {
expect(where({ DIFYCTL_PREFIX: '/opt/dify' })).toBe('/opt/dify/bin')
})
it('takes DIFYCTL_INSTALL_DIR as the bin folder itself, over DIFYCTL_PREFIX', () => {
expect(where({ DIFYCTL_PREFIX: '/opt/dify', DIFYCTL_INSTALL_DIR: '/usr/local/bin' })).toBe(
'/usr/local/bin',
)
})
})
describe('install-cli.sh install_binary', () => {
it('replaces the binary through a rename, leaving no staged file behind', () => {
const dir = mkdtempSync(join(tmpdir(), 'difyctl-install-'))
try {
const src = join(dir, 'new')
const dest = join(dir, 'bin-difyctl')
writeFileSync(src, 'new build')
writeFileSync(dest, 'old build')
const r = runLib(`install_binary "${src}" "${dest}"`)
expect(r.code).toBe(0)
expect(readFileSync(dest, 'utf8')).toBe('new build')
expect(execFileSync('ls', ['-A', dir], { encoding: 'utf8' }).trim().split('\n')).toEqual([
'bin-difyctl',
'new',
])
// Windows filesystems have no executable bit to check.
if (process.platform !== 'win32') {
expect(
execFileSync('sh', ['-c', `test -x "${dest}" && echo yes`], { encoding: 'utf8' }),
).toBe('yes\n')
}
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
// A shared install must stay readable by other users, whatever the installer's umask.
it.skipIf(process.platform === 'win32')(
'installs a 0600 source as mode 0755 under umask 077',
() => {
const dir = mkdtempSync(join(tmpdir(), 'difyctl-install-'))
try {
const src = join(dir, 'new')
const dest = join(dir, 'bin-difyctl')
writeFileSync(src, 'new build', { mode: 0o600 })
const r = runLib(`umask 077; install_binary "${src}" "${dest}"`)
expect(r.code).toBe(0)
expect(statSync(dest).mode & 0o777).toBe(0o755)
} finally {
rmSync(dir, { recursive: true, force: true })
}
},
)
it('dies without touching the old binary when the folder is not writable', () => {
const r = runLib('install_binary /nonexistent/src /nonexistent-dir/difyctl')
expect(r.code).not.toBe(0)
expect(r.stderr).toMatch(/cannot write \/nonexistent-dir\/difyctl/)
})
})
// A v2 binary answers `install skills --help`; a v1 one exits 1 with "unknown command".
describe.skipIf(process.platform === 'win32')('install-cli.sh print_skill_hint', () => {
const fakeBins = [
'd="$(mktemp -d)"',
'printf \'#!/bin/sh\\n[ "$*" = "install skills --help" ]\\n\' > "$d/v2"',
'printf \'#!/bin/sh\\necho "unknown command: $*" >&2\\nexit 1\\n\' > "$d/v1"',
'chmod 0755 "$d/v2" "$d/v1"',
]
it('prints the hint for a binary that has install skills', () => {
const r = runLib([...fakeBins, 'print_skill_hint "$d/v2"', 'rm -rf "$d"'].join('\n'))
expect(r.code).toBe(0)
expect(r.stdout).toMatch(/difyctl install skills <skills root>/)
})
it('prints nothing for a binary without install skills', () => {
const r = runLib([...fakeBins, 'print_skill_hint "$d/v1"', 'rm -rf "$d"'].join('\n'))
expect(r.code).toBe(0)
expect(r.stdout).toBe('')
})
it('prints nothing when the binary cannot run', () => {
const r = runLib('print_skill_hint /nonexistent/difyctl')
expect(r.code).toBe(0)
expect(r.stdout).toBe('')
})
})
+48
View File
@@ -0,0 +1,48 @@
#!/bin/sh
# install-local.sh — install difyctl from locally built standalone binaries.
# Run via: pnpm install:local (after `pnpm build:bin:local`)
#
# Consumes the raw, self-contained binaries emitted by scripts/release-build.sh
# into dist/bin (difyctl-v<ver>-<os>-<arch>). No GitHub Release needed: build on
# one machine, copy dist/bin to the tester, point this script at that directory.
set -eu
PREFIX="${DIFYCTL_PREFIX:-${HOME}/.local}"
SHARE_DIR="${PREFIX}/share/difyctl"
BIN_DIR="${PREFIX}/bin"
case "$(uname -s)" in
Linux*) os=linux ;;
Darwin*) os=darwin ;;
*) echo "unsupported OS: $(uname -s) (use install.ps1 on Windows)" >&2; exit 1 ;;
esac
case "$(uname -m)" in
x86_64|amd64) arch=x64 ;;
arm64|aarch64) arch=arm64 ;;
*) echo "unsupported arch: $(uname -m)" >&2; exit 1 ;;
esac
# Accept an optional directory path as the first argument.
# Default to the cli/dist/bin directory if not provided.
ARTIFACT_DIR="${1:-$(cd "$(dirname "$0")/../dist/bin" 2>/dev/null && pwd || true)}"
BINARY="$(ls "${ARTIFACT_DIR}"/difyctl-v*-${os}-${arch} 2>/dev/null | sort -V | tail -1)"
if [ -z "$BINARY" ]; then
echo "no binary found for ${os}-${arch} in ${ARTIFACT_DIR:-<unset>}" >&2
echo "run: pnpm build:bin:local" >&2
exit 1
fi
echo "installing from $(basename "$BINARY") ..."
rm -rf "$SHARE_DIR"
mkdir -p "${SHARE_DIR}/bin" "$BIN_DIR"
cp "$BINARY" "${SHARE_DIR}/bin/difyctl"
chmod +x "${SHARE_DIR}/bin/difyctl"
ln -sf "${SHARE_DIR}/bin/difyctl" "${BIN_DIR}/difyctl"
echo "installed: ${BIN_DIR}/difyctl"
case ":${PATH}:" in
*":${BIN_DIR}:"*) ;;
*) echo "note: add ${BIN_DIR} to your PATH" ;;
esac
+135
View File
@@ -0,0 +1,135 @@
# install-r2.ps1 — one-line difyctl installer (Windows) from Cloudflare R2.
# Usage: $env:DIFYCTL_R2_BASE='<BASE>'; irm https://raw.githubusercontent.com/langgenius/dify/main/cli/scripts/install-r2.ps1 | iex
# Env: DIFYCTL_R2_BASE (required), DIFYCTL_CHANNEL (default edge),
# DIFYCTL_INSTALL_DIR (default %LOCALAPPDATA%\difyctl\bin; binary written here as difyctl.exe),
# DIFYCTL_PREFIX (the folder above the bin folder; <prefix>\bin is used when DIFYCTL_INSTALL_DIR is unset),
# DIFYCTL_VERSION (pin exact published version),
# DIFYCTL_COMMIT (pin by git commit, short or full sha; via index.json),
# DIFYCTL_R2_PREFIX (default difyctl; key root for pointer JSONs),
# DIFYCTL_R2_BIN_PREFIX (default <prefix>/bin; key root for binaries).
# With no pin the channel pointer (latest) is installed.
$ErrorActionPreference = 'Stop'
function Get-TargetField($manifest, [string]$target, [string]$field) {
$t = $manifest.targets.$target
if (-not $t) { return $null }
return $t.$field
}
# First build in index.json matching by exact version or commit prefix.
function Resolve-IndexBuild($index, [string]$kind, [string]$want) {
foreach ($b in $index.builds) {
$sel = if ($kind -eq 'commit') { $b.commit } else { $b.version }
$hit = if ($kind -eq 'commit') { $sel.StartsWith($want) } else { $sel -eq $want }
if ($hit) { return $b }
}
return $null
}
# Parse a checksums.txt ("<sha> <asset>") for the line whose asset matches the
# target; returns @{ Sha; Asset } or $null.
function Get-ChecksumTarget([string]$text, [string]$target) {
foreach ($line in ($text -split "`n")) {
$line = $line.Trim()
if ($line -match "\sdifyctl-v.*-$target(\.exe)?$") {
$parts = $line -split '\s+'
return @{ Sha = $parts[0]; Asset = $parts[-1] }
}
}
return $null
}
# DIFYCTL_INSTALL_DIR names the bin folder itself; DIFYCTL_PREFIX the folder above it.
function Resolve-BinDir {
if ($env:DIFYCTL_INSTALL_DIR) { return $env:DIFYCTL_INSTALL_DIR }
$prefix = if ($env:DIFYCTL_PREFIX) { $env:DIFYCTL_PREFIX } else { Join-Path $env:LOCALAPPDATA 'difyctl' }
return Join-Path $prefix 'bin'
}
# The user PATH alone: $env:PATH also holds the machine PATH, which must not be copied into it.
function Get-PathHint([string]$Dir) {
return " [Environment]::SetEnvironmentVariable('PATH', `"$Dir;`" + [Environment]::GetEnvironmentVariable('PATH', 'User'), 'User')"
}
# The hint names a v2 command, so a binary without it (any v1 build) gets none. Under
# Windows PowerShell 5.1 a redirected stderr line throws when errors stop, hence the catch.
function Write-SkillHint([string]$Bin) {
if (-not (Test-Path -LiteralPath $Bin -PathType Leaf)) { return }
try { & $Bin install skills --help *> $null } catch { return }
if ($LASTEXITCODE -ne 0) { return }
Write-Host 'AI agents: run `difyctl install skills <skills root>` after each install or upgrade; the skill ships inside the binary.'
}
# Download, sha256-verify, place. Returns nothing; throws on a missing or wrong checksum.
function Install-DifyctlBinary([string]$dlUrl, [string]$sha, [string]$version, [string]$channel, [string]$installDir) {
if (-not $sha) { throw "no checksum published for $dlUrl; not installing an unverified binary" }
$tmp = Join-Path ([System.IO.Path]::GetTempPath()) ('difyctl-' + [guid]::NewGuid().ToString('N') + '.exe')
try {
Invoke-WebRequest -Uri $dlUrl -OutFile $tmp
$actual = (Get-FileHash -Path $tmp -Algorithm SHA256).Hash.ToLower()
if ($actual -ne $sha.ToLower()) { throw "checksum mismatch for $dlUrl" }
New-Item -ItemType Directory -Path $installDir -Force | Out-Null
$dest = Join-Path $installDir 'difyctl.exe'
try { Move-Item -Path $tmp -Destination $dest -Force }
catch { throw "cannot replace $dest — close any running difyctl and re-run." }
}
finally {
Remove-Item -Path $tmp -Force -ErrorAction SilentlyContinue
}
Write-Host "difyctl $version (channel $channel) installed: $dest"
if (($env:PATH -split ';') -notcontains $installDir) {
Write-Host "$installDir is not on your PATH. Add it with:"
Write-Host (Get-PathHint $installDir)
}
else {
Write-SkillHint $dest
}
}
function Install-DifyctlR2 {
$base = $env:DIFYCTL_R2_BASE
if (-not $base) { throw "set DIFYCTL_R2_BASE to the R2 public base (e.g. https://pub-….r2.dev)" }
$base = $base.TrimEnd('/')
$channel = if ($env:DIFYCTL_CHANNEL) { $env:DIFYCTL_CHANNEL } else { 'edge' }
$prefix = if ($env:DIFYCTL_R2_PREFIX) { $env:DIFYCTL_R2_PREFIX } else { 'difyctl' }
$binPrefix = if ($env:DIFYCTL_R2_BIN_PREFIX) { $env:DIFYCTL_R2_BIN_PREFIX } else { "$prefix/bin" }
$installDir = Resolve-BinDir
$target = 'windows-x64'
if ($env:DIFYCTL_VERSION -or $env:DIFYCTL_COMMIT) {
$iurl = "$base/$prefix/$channel/index.json"
try { $index = Invoke-RestMethod -Uri $iurl }
catch { throw "R2 unavailable fetching $iurl; retry." }
$build = if ($env:DIFYCTL_VERSION) { Resolve-IndexBuild $index 'version' $env:DIFYCTL_VERSION }
else { Resolve-IndexBuild $index 'commit' $env:DIFYCTL_COMMIT }
$pin = if ($env:DIFYCTL_VERSION) { $env:DIFYCTL_VERSION } else { $env:DIFYCTL_COMMIT }
if (-not $build) { throw "no build matching $pin in channel $channel" }
$version = $build.version
$vbase = "$base/$binPrefix/$channel/$($build.dir)"
try { $cf = (Invoke-WebRequest -Uri "$vbase/difyctl-v$version-checksums.txt").Content }
catch { throw "checksums missing for $version (channel $channel)" }
$ct = Get-ChecksumTarget $cf $target
if (-not $ct) { throw "no build for $target at $version" }
Install-DifyctlBinary "$vbase/$($ct.Asset)" $ct.Sha $version $channel $installDir
return
}
$murl = "$base/$prefix/$channel/manifest.json"
try { $manifest = Invoke-RestMethod -Uri $murl }
catch {
if ($_.Exception.Response.StatusCode.value__ -eq 404) {
throw "channel '$channel' not published to R2. For rc/stable use install.ps1 (GitHub)."
}
throw "R2 unavailable fetching $murl; retry."
}
if ($manifest.channel -ne $channel) { throw "manifest channel '$($manifest.channel)' != requested '$channel'" }
$asset = Get-TargetField $manifest $target 'asset'
$sha = Get-TargetField $manifest $target 'sha256'
if (-not $asset) { throw "no build for $target in channel $channel" }
Install-DifyctlBinary "$($manifest.baseUrl)/$asset" $sha $manifest.version $channel $installDir
}
if ($env:DIFYCTL_INSTALL_LIB -ne '1') { Install-DifyctlR2 }
@@ -0,0 +1,139 @@
import { spawnSync } from 'node:child_process'
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { describe, expect, it, vi } from 'vite-plus/test'
const SCRIPT = fileURLToPath(new URL('./install-r2.ps1', import.meta.url))
const hasPwsh = spawnSync('pwsh', ['-v'], { encoding: 'utf8' }).status === 0
// Each test starts pwsh; cold starts on a busy CI runner can exceed the default 5 seconds.
if (hasPwsh) vi.setConfig({ testTimeout: 15_000 })
const d = hasPwsh ? describe : describe.skip
const MANIFEST = JSON.stringify({
schema: 1,
name: 'difyctl',
channel: 'edge',
version: '0.1.0-edge.2fd7b82',
baseUrl: 'https://pub.example.r2.dev/difyctl/edge/0.1.0-edge.2fd7b82',
targets: {
'windows-x64': { asset: 'difyctl-v0.1.0-edge.2fd7b82-windows-x64.exe', sha256: 'deadbeef' },
},
})
function pwsh(
program: string,
env: Record<string, string> = {},
): { code: number; stdout: string; stderr: string } {
const full = `. '${SCRIPT}'\n${program}`
const r = spawnSync('pwsh', ['-NoProfile', '-Command', full], {
encoding: 'utf8',
env: { ...process.env, DIFYCTL_INSTALL_LIB: '1', ...env },
})
return {
code: r.status ?? 1,
stdout: (r.stdout ?? '').replace(/\r\n/g, '\n').trim(),
stderr: r.stderr ?? '',
}
}
d('install-r2.ps1', () => {
it('parses a target asset + sha from the manifest', () => {
const prog =
`$m = ConvertFrom-Json @'\n${MANIFEST}\n'@\n` +
`Write-Output (Get-TargetField $m 'windows-x64' 'asset')\n` +
`Write-Output (Get-TargetField $m 'windows-x64' 'sha256')`
const { stdout } = pwsh(prog)
expect(stdout).toBe('difyctl-v0.1.0-edge.2fd7b82-windows-x64.exe\ndeadbeef')
})
it('errors when DIFYCTL_R2_BASE is unset', () => {
const r = spawnSync('pwsh', ['-NoProfile', '-File', SCRIPT], {
encoding: 'utf8',
env: { ...process.env, DIFYCTL_R2_BASE: '' },
})
if (hasPwsh) {
expect(r.status).not.toBe(0)
expect(r.stderr + r.stdout).toMatch(/DIFYCTL_R2_BASE/)
}
})
})
d('install-r2.ps1 install location, PATH hint and download', () => {
const where = (env: Record<string, string>) =>
pwsh('Write-Output (Resolve-BinDir)', {
DIFYCTL_PREFIX: '',
DIFYCTL_INSTALL_DIR: '',
LOCALAPPDATA: '/lad',
...env,
}).stdout
it('defaults to %LOCALAPPDATA%\\difyctl\\bin', () => {
expect(where({})).toBe(join('/lad', 'difyctl', 'bin'))
})
it('accepts DIFYCTL_PREFIX like the GitHub installer', () => {
expect(where({ DIFYCTL_PREFIX: '/opt/dify' })).toBe(join('/opt/dify', 'bin'))
})
it('keeps DIFYCTL_INSTALL_DIR as the bin folder itself, over DIFYCTL_PREFIX', () => {
expect(where({ DIFYCTL_PREFIX: '/opt/dify', DIFYCTL_INSTALL_DIR: '/custom/bin' })).toBe(
'/custom/bin',
)
})
it('the PATH command adds to the user PATH, not the whole session PATH', () => {
const hint = pwsh(`Write-Output (Get-PathHint 'C:\\dify\\bin')`).stdout
expect(hint).toContain(
`"C:\\dify\\bin;" + [Environment]::GetEnvironmentVariable('PATH', 'User')`,
)
expect(hint).not.toContain('$env:PATH')
})
it('stops before downloading when the checksum is missing', () => {
const r = pwsh(
"function Invoke-WebRequest { throw 'must not download' }\n" +
"try { Install-DifyctlBinary 'https://x/difyctl.exe' '' '1.0.0' 'edge' '/tmp/none' } " +
'catch { Write-Output $_.Exception.Message }',
)
expect(r.stdout).toMatch(/^no checksum published for https:\/\/x\/difyctl\.exe/)
})
it('downloads to a unique temp file, not one named after the asset', () => {
const r = pwsh(
'function Invoke-WebRequest { param($Uri, $OutFile) Write-Output "OUT=$OutFile"; Set-Content -Path $OutFile -Value x }\n' +
"try { Install-DifyctlBinary 'https://x/difyctl.exe' 'deadbeef' '1.0.0' 'edge' '/tmp/none' } " +
'catch { Write-Output $_.Exception.Message }',
)
expect(r.stdout).toMatch(/OUT=.*difyctl-[0-9a-f]{32}\.exe\n/)
expect(r.stdout).toMatch(/checksum mismatch/)
})
})
// A v2 binary answers `install skills --help`; a v1 one exits 1 with "unknown command".
// The fakes are shell scripts, so this runs where pwsh runs outside Windows.
describe.skipIf(!hasPwsh || process.platform === 'win32')('install-r2.ps1 Write-SkillHint', () => {
const hint = (bin: string) => pwsh(`Write-SkillHint '${bin}'`)
it('prints the hint for a binary that has install skills, and stays quiet otherwise', () => {
const dir = mkdtempSync(join(tmpdir(), 'difyctl-hint-'))
try {
const v2 = join(dir, 'v2')
const v1 = join(dir, 'v1')
writeFileSync(v2, '#!/bin/sh\n[ "$*" = "install skills --help" ]\n', { mode: 0o755 })
writeFileSync(v1, '#!/bin/sh\necho "unknown command: $*" >&2\nexit 1\n', { mode: 0o755 })
expect(hint(v2)).toMatchObject({
code: 0,
stdout: expect.stringContaining('difyctl install skills <skills root>'),
})
expect(hint(v1)).toMatchObject({ code: 0, stdout: '' })
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
it('prints nothing when the binary cannot run', () => {
expect(hint('/nonexistent/difyctl')).toMatchObject({ code: 0, stdout: '' })
})
})
+185
View File
@@ -0,0 +1,185 @@
#!/bin/sh
# install-r2.sh — one-line difyctl installer from Cloudflare R2.
# Reads a per-channel pointer manifest, sha256-verifies, installs to PATH.
# Usage: curl -fsSL https://raw.githubusercontent.com/langgenius/dify/main/cli/scripts/install-r2.sh | DIFYCTL_R2_BASE=<BASE> sh
# Env:
# DIFYCTL_R2_BASE (required) R2 public base, e.g. https://pub-….r2.dev
# DIFYCTL_CHANNEL (default edge)
# DIFYCTL_INSTALL_DIR (default $HOME/.local/bin) directory the binary is written to as <dir>/difyctl
# DIFYCTL_PREFIX the folder above the bin folder; <prefix>/bin is used when DIFYCTL_INSTALL_DIR is unset
# DIFYCTL_VERSION pin an exact published version (e.g. 0.1.0-edge.ce4af868)
# DIFYCTL_COMMIT pin by git commit (short or full sha); resolved via index.json
# DIFYCTL_R2_PREFIX (default difyctl) key root for pointer JSONs
# DIFYCTL_R2_BIN_PREFIX (default <prefix>/bin) key root for binaries
# With no pin the channel pointer (latest) is installed. A pin resolves through
# <prefix>/<channel>/index.json -> the build's immutable dir under the bin prefix.
set -eu
# --- library functions (sourced for tests when DIFYCTL_INSTALL_LIB=1) ---
tmp_m="$(mktemp 2>/dev/null || echo /tmp/difyctl-manifest.$$)"
trap 'rm -f "$tmp_m" "${tmp_c:-}" "${tmp_b:-}"' EXIT INT TERM
err() { printf '%s\n' "install-r2: $*" >&2; }
die() { err "$*"; exit 1; }
need() { command -v "$1" >/dev/null 2>&1 || die "$1 is required"; }
# print_skill_hint BIN: the hint names a v2 command, so a binary without it (any v1 build) gets none.
print_skill_hint() {
"$1" install skills --help >/dev/null 2>&1 || return 0
printf '%s\n' 'AI agents: run `difyctl install skills <skills root>` after each install or upgrade; the skill ships inside the binary.'
}
# DIFYCTL_INSTALL_DIR names the bin folder itself; DIFYCTL_PREFIX the folder above it.
bin_dir_for() {
printf '%s' "${DIFYCTL_INSTALL_DIR:-${DIFYCTL_PREFIX:-${HOME}/.local}/bin}"
}
# install_binary SRC DEST: stage the copy next to DEST, then rename it over DEST, so a
# running difyctl keeps its old file and DEST is never half written.
install_binary() {
_stage="$(dirname "$2")/.difyctl.install.$$"
if cp "$1" "$_stage" && chmod 0755 "$_stage" && mv -f "$_stage" "$2"; then
return 0
fi
rm -f "$_stage"
die "cannot write $2"
}
detect_target() {
case "$(uname -s)" in
Linux*) _os=linux ;;
Darwin*) _os=darwin ;;
*) die "unsupported OS: $(uname -s) (use install-r2.ps1 on Windows)" ;;
esac
case "$(uname -m)" in
x86_64|amd64) _arch=x64 ;;
arm64|aarch64) _arch=arm64 ;;
*) die "unsupported arch: $(uname -m)" ;;
esac
printf '%s-%s' "$_os" "$_arch"
}
# grep/sed (no jq). Correct only because release-r2-edge.mjs renders one key per line.
# manifest_str <file> <key> -> value of a top-level string field
manifest_str() {
grep "\"$2\"[[:space:]]*:" "$1" | head -1 \
| sed -E "s/.*\"$2\"[[:space:]]*:[[:space:]]*\"([^\"]+)\".*/\\1/"
}
# manifest_target_field <file> <target-id> <asset|sha256> -> value on that target's line
manifest_target_field() {
grep "\"$2\"[[:space:]]*:" "$1" | head -1 \
| sed -E "s/.*\"$3\"[[:space:]]*:[[:space:]]*\"([^\"]+)\".*/\\1/"
}
# Resolve a pinned build from index.json (no jq). Correct only because
# release-r2-edge.mjs renders each build's fields one per line, dir last.
# Prints "<version>\t<dir>" of the first match, nothing if none.
# index_resolve <index-file> <kind:version|commit> <value> (commit = prefix match)
index_resolve() {
awk -v kind="$2" -v want="$3" '
function val(s) { sub(/^[^:]*:[[:space:]]*"/, "", s); sub(/".*$/, "", s); return s }
/"version"[[:space:]]*:/ { v = val($0) }
/"commit"[[:space:]]*:/ { c = val($0) }
/"dir"[[:space:]]*:/ {
d = val($0)
sel = (kind == "commit") ? c : v
if (kind == "commit") { if (index(sel, want) == 1) { print v "\t" d; exit } }
else if (sel == want) { print v "\t" d; exit }
}
' "$1"
}
# checksums_target <checksums-file> <target-id> -> "<sha256>\t<asset>"
# checksums lines are "<sha> <asset>"; match asset ending -<target> or -<target>.exe.
checksums_target() {
grep -E "[[:space:]]difyctl-v.*-$2(\.exe)?\$" "$1" | head -1 \
| awk '{ print $1 "\t" $NF }'
}
sha256_check() {
# $1 = file, $2 = expected hex
if command -v sha256sum >/dev/null 2>&1; then _a="$(sha256sum "$1" | awk '{print $1}')"
elif command -v shasum >/dev/null 2>&1; then _a="$(shasum -a 256 "$1" | awk '{print $1}')"
else die "no sha256 tool (need sha256sum or shasum)"; fi
[ "$_a" = "$2" ] || die "checksum mismatch for $1"
}
# fetch_verify_install <download-url> <expected-sha> <version> <channel>
fetch_verify_install() {
tmp_b="$(mktemp)"
# NOTE: no --compressed — must hash the raw bytes
curl -fsSL "$1" -o "$tmp_b" || die "download failed: $1"
sha256_check "$tmp_b" "$2"
mkdir -p "$install_dir"
install_binary "$tmp_b" "${install_dir}/difyctl"
printf 'difyctl %s (channel %s) installed: %s\n' "$3" "$4" "${install_dir}/difyctl"
case ":${PATH}:" in
*":${install_dir}:"*) print_skill_hint "${install_dir}/difyctl" ;;
*) printf 'note: add %s to your PATH\n' "$install_dir" ;;
esac
}
# Resolve a pinned build into download url + sha. Sets: version, dl_url, dl_sha.
resolve_pinned() {
iurl="${base}/${prefix}/${channel}/index.json"
curl -fsSL "$iurl" -o "$tmp_m" || die "R2 unavailable fetching ${iurl}; retry."
if [ -n "${DIFYCTL_VERSION:-}" ]; then res="$(index_resolve "$tmp_m" version "$DIFYCTL_VERSION")"
else res="$(index_resolve "$tmp_m" commit "$DIFYCTL_COMMIT")"; fi
[ -n "$res" ] || die "no build matching ${DIFYCTL_VERSION:-$DIFYCTL_COMMIT} in channel ${channel}"
version="$(printf '%s' "$res" | cut -f1)"
dir="$(printf '%s' "$res" | cut -f2)"
vbase="${base}/${bin_prefix}/${channel}/${dir}"
tmp_c="$(mktemp)"
curl -fsSL "${vbase}/difyctl-v${version}-checksums.txt" -o "$tmp_c" \
|| die "checksums missing for ${version} (channel ${channel})"
line="$(checksums_target "$tmp_c" "$target")"
[ -n "$line" ] || die "no build for ${target} at ${version}"
dl_sha="$(printf '%s' "$line" | cut -f1)"
dl_url="${vbase}/$(printf '%s' "$line" | cut -f2)"
}
# Resolve the channel pointer (latest) into download url + sha. Sets the same.
resolve_pointer() {
murl="${base}/${prefix}/${channel}/manifest.json"
_code="$(curl -fsS -o "$tmp_m" -w '%{http_code}' "$murl" 2>/dev/null || true)"
if [ ! -s "$tmp_m" ]; then
case "$_code" in
404) die "channel '${channel}' not published to R2. For rc/stable use the GitHub installer (install-cli.sh)." ;;
*) die "R2 unavailable (HTTP ${_code:-?}) fetching ${murl}; retry." ;;
esac
fi
mchannel="$(manifest_str "$tmp_m" channel)"
[ "$mchannel" = "$channel" ] || die "manifest channel '${mchannel}' != requested '${channel}'"
version="$(manifest_str "$tmp_m" version)"
baseUrl="$(manifest_str "$tmp_m" baseUrl)"
asset="$(manifest_target_field "$tmp_m" "$target" asset)"
dl_sha="$(manifest_target_field "$tmp_m" "$target" sha256)"
[ -n "$asset" ] && [ -n "$dl_sha" ] || die "no build for ${target} in channel ${channel}"
dl_url="${baseUrl}/${asset}"
}
install_main() {
need curl
[ -n "${DIFYCTL_R2_BASE:-}" ] || die "set DIFYCTL_R2_BASE to the R2 public base (e.g. https://pub-….r2.dev)"
base="${DIFYCTL_R2_BASE%/}"
channel="${DIFYCTL_CHANNEL:-edge}"
prefix="${DIFYCTL_R2_PREFIX:-difyctl}"
bin_prefix="${DIFYCTL_R2_BIN_PREFIX:-${prefix}/bin}"
install_dir="$(bin_dir_for)"
target="$(detect_target)"
if [ -n "${DIFYCTL_VERSION:-}" ] || [ -n "${DIFYCTL_COMMIT:-}" ]; then
resolve_pinned
else
resolve_pointer
fi
fetch_verify_install "$dl_url" "$dl_sha" "$version" "$channel"
}
if [ "${DIFYCTL_INSTALL_LIB:-0}" != "1" ]; then
install_main
fi
@@ -0,0 +1,222 @@
import { spawnSync } from 'node:child_process'
import { fileURLToPath } from 'node:url'
import { describe, expect, it } from 'vite-plus/test'
const SCRIPT = fileURLToPath(new URL('./install-r2.sh', import.meta.url))
const MANIFEST = [
'{',
' "schema": 1,',
' "name": "difyctl",',
' "channel": "edge",',
' "version": "0.1.0-edge.2fd7b82",',
' "commit": "abc1234",',
' "buildDate": "2026-06-14T12:00:00Z",',
' "baseUrl": "https://pub.example.r2.dev/difyctl/edge/0.1.0-edge.2fd7b82",',
' "targets": {',
' "linux-x64": { "asset": "difyctl-v0.1.0-edge.2fd7b82-linux-x64", "sha256": "deadbeef" },',
' "darwin-arm64": { "asset": "difyctl-v0.1.0-edge.2fd7b82-darwin-arm64", "sha256": "cafef00d" }',
' }',
'}',
].join('\n')
const INDEX = [
'{',
' "schema": 1,',
' "channel": "edge",',
' "updated": "2026-06-15T00:00:00Z",',
' "builds": [',
' {',
' "version": "0.1.0-edge.ce4af868",',
' "commit": "ce4af868d653f405070fabb3be3303430cc030ad",',
' "buildDate": "2026-06-15T00:00:00Z",',
' "dir": "0.1.0-edge.ce4af868"',
' },',
' {',
' "version": "0.1.0-edge.aaaa111",',
' "commit": "aaaa111bbbbcccc000011112222333344445555",',
' "buildDate": "2026-06-14T00:00:00Z",',
' "dir": "0.1.0-edge.aaaa111"',
' }',
' ]',
'}',
].join('\n')
const CHECKSUMS = [
'deadbeef difyctl-v0.1.0-edge.ce4af868-linux-x64',
'cafef00d difyctl-v0.1.0-edge.ce4af868-darwin-arm64',
'beadc0de difyctl-v0.1.0-edge.ce4af868-windows-x64.exe',
].join('\n')
function lib(
program: string,
env: Record<string, string> = {},
): { code: number; stdout: string; stderr: string } {
const full = `. "${SCRIPT}"\n${program}`
const r = spawnSync('sh', ['-c', full], {
encoding: 'utf8',
env: { ...process.env, DIFYCTL_INSTALL_LIB: '1', ...env },
})
return { code: r.status ?? 1, stdout: (r.stdout ?? '').trim(), stderr: r.stderr ?? '' }
}
describe('install-r2 manifest parsing', () => {
// install-r2.sh is POSIX-only; under git-bash on Windows `uname -s` is MINGW*,
// so detect_target intentionally dies (Windows installs go through install-r2.ps1).
it.skipIf(process.platform === 'win32')('detect_target maps to one of the 5 ids', () => {
const { stdout } = lib('detect_target')
expect(['linux-x64', 'linux-arm64', 'darwin-x64', 'darwin-arm64', 'windows-x64']).toContain(
stdout,
)
})
it('manifest_str reads a top-level string field', () => {
const { stdout } = lib(
`printf '%s' '${MANIFEST}' > "$tmp_m"; manifest_str "$tmp_m" channel`,
{},
)
expect(stdout).toBe('edge')
})
it('manifest_target_field extracts per-target values from a single line', () => {
const prog =
`printf '%s' '${MANIFEST}' > "$tmp_m"\n` +
'manifest_target_field "$tmp_m" darwin-arm64 asset\n' +
'manifest_target_field "$tmp_m" darwin-arm64 sha256'
const { stdout } = lib(prog)
expect(stdout).toBe('difyctl-v0.1.0-edge.2fd7b82-darwin-arm64\ncafef00d')
})
it('requires DIFYCTL_R2_BASE when run as the installer (not lib)', () => {
const r = spawnSync('sh', [SCRIPT], {
encoding: 'utf8',
env: { ...process.env, DIFYCTL_R2_BASE: '' },
})
expect(r.status).not.toBe(0)
expect(r.stderr).toMatch(/DIFYCTL_R2_BASE/)
})
it('sha256_check aborts on a checksum mismatch', () => {
const r = lib('f="$(mktemp)"; printf \'hello\' > "$f"; sha256_check "$f" deadbeef')
expect(r.code).not.toBe(0)
expect(r.stderr).toMatch(/checksum mismatch/)
})
it('sha256_check passes on the correct hash', () => {
// sha256('hello') = 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
const r = lib(
'f="$(mktemp)"; printf \'hello\' > "$f"; sha256_check "$f" 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824 && echo OK',
)
expect(r.stdout).toBe('OK')
})
})
describe('install-r2 version/commit pin', () => {
it('index_resolve matches a build by exact version', () => {
const r = lib(
`printf '%s' '${INDEX}' > "$tmp_m"; index_resolve "$tmp_m" version 0.1.0-edge.aaaa111`,
)
expect(r.stdout).toBe('0.1.0-edge.aaaa111\t0.1.0-edge.aaaa111')
})
it('index_resolve matches a build by commit prefix', () => {
const r = lib(`printf '%s' '${INDEX}' > "$tmp_m"; index_resolve "$tmp_m" commit ce4af868`)
expect(r.stdout).toBe('0.1.0-edge.ce4af868\t0.1.0-edge.ce4af868')
})
it('index_resolve matches the full 40-char commit too', () => {
const r = lib(
`printf '%s' '${INDEX}' > "$tmp_m"; index_resolve "$tmp_m" commit aaaa111bbbbcccc000011112222333344445555`,
)
expect(r.stdout).toBe('0.1.0-edge.aaaa111\t0.1.0-edge.aaaa111')
})
it('index_resolve prints nothing when no build matches', () => {
const r = lib(`printf '%s' '${INDEX}' > "$tmp_m"; index_resolve "$tmp_m" commit ffffff`)
expect(r.stdout).toBe('')
})
it('checksums_target extracts sha and asset for a posix target', () => {
const r = lib(`printf '%s' '${CHECKSUMS}' > "$tmp_m"; checksums_target "$tmp_m" darwin-arm64`)
expect(r.stdout).toBe('cafef00d\tdifyctl-v0.1.0-edge.ce4af868-darwin-arm64')
})
it('checksums_target does not bleed x64 into arm64', () => {
const r = lib(`printf '%s' '${CHECKSUMS}' > "$tmp_m"; checksums_target "$tmp_m" linux-x64`)
expect(r.stdout).toBe('deadbeef\tdifyctl-v0.1.0-edge.ce4af868-linux-x64')
})
})
describe('install-r2.sh install location', () => {
const where = (env: Record<string, string>) =>
lib('bin_dir_for', { DIFYCTL_PREFIX: '', DIFYCTL_INSTALL_DIR: '', HOME: '/home/u', ...env })
.stdout
it('defaults to ~/.local/bin', () => {
expect(where({})).toBe('/home/u/.local/bin')
})
it('accepts DIFYCTL_PREFIX like the GitHub installer', () => {
expect(where({ DIFYCTL_PREFIX: '/opt/dify' })).toBe('/opt/dify/bin')
})
it('keeps DIFYCTL_INSTALL_DIR as the bin folder itself, over DIFYCTL_PREFIX', () => {
expect(where({ DIFYCTL_PREFIX: '/opt/dify', DIFYCTL_INSTALL_DIR: '/usr/local/bin' })).toBe(
'/usr/local/bin',
)
})
})
it.skipIf(process.platform === 'win32')(
'install-r2.sh points Windows users at install-r2.ps1',
() => {
const r = lib('uname() { printf MINGW64_NT; }; detect_target')
expect(r.code).not.toBe(0)
expect(r.stderr).toMatch(/use install-r2\.ps1 on Windows/)
},
)
describe.skipIf(process.platform === 'win32')('install-r2.sh install_binary', () => {
it('installs a 0600 temp file as mode 0755 next to and then over the target', () => {
const r = lib(
[
'd="$(mktemp -d)"',
'src="$(mktemp)"; chmod 0600 "$src"; printf new > "$src"',
'printf old > "$d/difyctl"',
'install_binary "$src" "$d/difyctl"',
'ls -l "$d/difyctl" | cut -c1-10; cat "$d/difyctl"; echo; ls -A "$d"',
'rm -rf "$d" "$src"',
].join('\n'),
)
expect(r.code).toBe(0)
expect(r.stdout.split('\n')).toEqual(['-rwxr-xr-x', 'new', 'difyctl'])
})
})
// A v2 binary answers `install skills --help`; a v1 one exits 1 with "unknown command".
describe.skipIf(process.platform === 'win32')('install-r2.sh print_skill_hint', () => {
const fakeBins = [
'd="$(mktemp -d)"',
'printf \'#!/bin/sh\\n[ "$*" = "install skills --help" ]\\n\' > "$d/v2"',
'printf \'#!/bin/sh\\necho "unknown command: $*" >&2\\nexit 1\\n\' > "$d/v1"',
'chmod 0755 "$d/v2" "$d/v1"',
]
it('prints the hint for a binary that has install skills', () => {
const r = lib([...fakeBins, 'print_skill_hint "$d/v2"', 'rm -rf "$d"'].join('\n'))
expect(r.code).toBe(0)
expect(r.stdout).toMatch(/difyctl install skills <skills root>/)
})
it('prints nothing for a binary without install skills', () => {
const r = lib([...fakeBins, 'print_skill_hint "$d/v1"', 'rm -rf "$d"'].join('\n'))
expect(r.code).toBe(0)
expect(r.stdout).toBe('')
})
it('prints nothing when the binary cannot run', () => {
const r = lib('print_skill_hint /nonexistent/difyctl')
expect(r.code).toBe(0)
expect(r.stdout).toBe('')
})
})
+198
View File
@@ -0,0 +1,198 @@
# install.ps1 — one-line difyctl installer for Windows. difyctl ships as assets
# on Dify GitHub Releases; this installs the build matching your Dify version.
#
# usage:
# irm https://raw.githubusercontent.com/langgenius/dify/main/cli/scripts/install.ps1 | iex
#
# env:
# DIFY_VERSION Dify release tag to install difyctl from (e.g. 1.14.2). Primary key.
# DIFYCTL_VERSION difyctl version pin (used only when DIFY_VERSION is unset).
# DIFYCTL_PREFIX install prefix (default $env:LOCALAPPDATA\difyctl); binary -> <prefix>\bin\difyctl.exe
# DIFYCTL_INSTALL_DIR the bin folder itself (wins over DIFYCTL_PREFIX); binary -> <dir>\difyctl.exe
# DIFYCTL_REPO release source repo (default langgenius/dify)
# GITHUB_TOKEN GitHub token (or GH_TOKEN) sent as a bearer to raise the API
# rate limit from 60 to 5000 requests/hour (useful in CI).
$ErrorActionPreference = 'Stop'
$repo = if ($env:DIFYCTL_REPO) { $env:DIFYCTL_REPO } else { 'langgenius/dify' }
$difyVersion = $env:DIFY_VERSION
$difyctlVersion = $env:DIFYCTL_VERSION
$target = 'windows-x64'
$apiBase = "https://api.github.com/repos/$repo"
$dlBase = "https://github.com/$repo/releases/download"
$headers = @{ Accept = 'application/vnd.github+json' }
$ghToken = if ($env:GITHUB_TOKEN) { $env:GITHUB_TOKEN } elseif ($env:GH_TOKEN) { $env:GH_TOKEN } else { $null }
if ($ghToken) { $headers.Authorization = "Bearer $ghToken" }
# Read a response header, coping with both PS7 (TryGetValues) and PS5.1 (indexer).
function Get-HeaderValue($Response, [string]$Name) {
if (-not $Response -or -not $Response.Headers) { return $null }
try {
$vals = $null
if ($Response.Headers.TryGetValues($Name, [ref]$vals)) { return ($vals | Select-Object -First 1) }
return $null
}
catch {
try { return $Response.Headers[$Name] } catch { return $null }
}
}
# $null unless the error is a GitHub rate limit; else an object with the reset epoch.
function Get-RateLimitInfo($ErrorRecord) {
$resp = $null
try { $resp = $ErrorRecord.Exception.Response } catch { return $null }
if (-not $resp) { return $null }
$status = 0; try { $status = [int]$resp.StatusCode } catch {}
if ($status -ne 403 -and $status -ne 429) { return $null }
$remaining = Get-HeaderValue $resp 'x-ratelimit-remaining'
if ($status -eq 429 -or $remaining -eq '0') {
return [pscustomobject]@{ Reset = (Get-HeaderValue $resp 'x-ratelimit-reset') }
}
return $null
}
function Write-RateLimitHint($ResetEpoch) {
[Console]::Error.WriteLine('GitHub API rate limit exceeded (unauthenticated requests are capped at 60/hour per IP).')
if ("$ResetEpoch" -match '^\d+$') {
$mins = [int][math]::Ceiling(([long]$ResetEpoch - [DateTimeOffset]::UtcNow.ToUnixTimeSeconds()) / 60)
if ($mins -gt 0) { [Console]::Error.WriteLine("The limit resets in ~$mins min.") }
}
[Console]::Error.WriteLine('To proceed now, authenticate to raise the limit to 5000/hour:')
[Console]::Error.WriteLine(' $env:GITHUB_TOKEN = "<token>"; irm <install-url> | iex')
[Console]::Error.WriteLine('Tip: pinning DIFY_VERSION makes a single API call (DIFYCTL_VERSION scans many).')
}
# Print the hint and exit if rate-limited; else return so the caller can throw.
function Stop-IfRateLimited($ErrorRecord) {
$info = Get-RateLimitInfo $ErrorRecord
if (-not $info) { return }
Write-RateLimitHint $info.Reset
exit 1
}
function Get-AssetSemver([string]$Name) {
if ($Name -notmatch '^difyctl-v(.+?)-windows-x64\.exe$') { return $null }
$v = $Matches[1]
$core = (($v -split '\+')[0] -split '-')[0]
if ($core -notmatch '^\d+\.\d+\.\d+$') { return $null }
$rc = if ($v -match '-rc\.(\d+)') { [int]$Matches[1] } else { [int]::MaxValue }
return [pscustomobject]@{ Name = $Name; Version = $v; Core = [version]$core; Rc = $rc }
}
function Select-Asset([object]$Release) {
$Release.assets |
ForEach-Object { Get-AssetSemver $_.name } |
Where-Object { $_ } |
Sort-Object Core, Rc |
Select-Object -Last 1
}
function Find-ReleaseForDifyctl([string]$Want) {
try { $releases = Invoke-RestMethod -Uri "$apiBase/releases?per_page=100" -Headers $headers }
catch { Stop-IfRateLimited $_; throw }
foreach ($rel in $releases) {
$asset = Select-Asset $rel
if ($asset -and $asset.Version -eq $Want) { return $rel }
}
return $null
}
function Resolve-Release {
if ($difyVersion) {
try { return Invoke-RestMethod -Uri "$apiBase/releases/tags/$difyVersion" -Headers $headers }
catch { Stop-IfRateLimited $_; throw "Dify release $difyVersion not found: $_" }
}
elseif ($difyctlVersion) {
$release = Find-ReleaseForDifyctl $difyctlVersion
if (-not $release) { throw "difyctl $difyctlVersion not found on any Dify release" }
return $release
}
else {
try { return Invoke-RestMethod -Uri "$apiBase/releases/latest" -Headers $headers }
catch { Stop-IfRateLimited $_; throw "failed to query latest Dify release (set DIFY_VERSION to pin one): $_" }
}
}
# DIFYCTL_INSTALL_DIR names the bin folder itself; DIFYCTL_PREFIX the folder above it.
function Resolve-BinDir {
if ($env:DIFYCTL_INSTALL_DIR) { return $env:DIFYCTL_INSTALL_DIR }
$prefix = if ($env:DIFYCTL_PREFIX) { $env:DIFYCTL_PREFIX } else { Join-Path $env:LOCALAPPDATA 'difyctl' }
return Join-Path $prefix 'bin'
}
# The user PATH alone: $env:PATH also holds the machine PATH, which must not be copied into it.
function Get-PathHint([string]$Dir) {
return " [Environment]::SetEnvironmentVariable('PATH', `"$Dir;`" + [Environment]::GetEnvironmentVariable('PATH', 'User'), 'User')"
}
# The hint names a v2 command, so a binary without it (any v1 build) gets none. Under
# Windows PowerShell 5.1 a redirected stderr line throws when errors stop, hence the catch.
function Write-SkillHint([string]$Bin) {
if (-not (Test-Path -LiteralPath $Bin -PathType Leaf)) { return }
try { & $Bin install skills --help *> $null } catch { return }
if ($LASTEXITCODE -ne 0) { return }
Write-Host 'AI agents: run `difyctl install skills <skills root>` after each install or upgrade; the skill ships inside the binary.'
}
function Invoke-Main {
$release = Resolve-Release
$difyTag = $release.tag_name
$asset = Select-Asset $release
if (-not $asset) { throw "no difyctl published for Dify $difyTag (target $target); set DIFY_VERSION to a release that has one" }
$assetName = $asset.Name
$ver = $asset.Version
$checksums = "difyctl-v$ver-checksums.txt"
$base = "$dlBase/$difyTag"
$tmp = Join-Path $env:TEMP ("difyctl-" + [guid]::NewGuid().ToString('N'))
New-Item -ItemType Directory -Path $tmp -Force | Out-Null
try {
Write-Host "downloading $assetName (Dify $difyTag)..."
$assetPath = Join-Path $tmp $assetName
$sumsPath = Join-Path $tmp $checksums
Invoke-WebRequest -Uri "$base/$assetName" -OutFile $assetPath
Invoke-WebRequest -Uri "$base/$checksums" -OutFile $sumsPath
$expected = (Get-Content $sumsPath |
Where-Object { $_ -match '\s' + [regex]::Escape($assetName) + '$' } |
ForEach-Object { ($_ -split '\s+')[0] } |
Select-Object -First 1)
if (-not $expected) { throw "no checksum entry for $assetName" }
$actual = (Get-FileHash -Path $assetPath -Algorithm SHA256).Hash.ToLower()
if ($actual -ne $expected.ToLower()) { throw "checksum mismatch for $assetName" }
$binDir = Resolve-BinDir
New-Item -ItemType Directory -Path $binDir -Force | Out-Null
$targetBin = Join-Path $binDir 'difyctl.exe'
# Stage next to the target, then rename over it, so difyctl.exe is never half written.
$stage = Join-Path $binDir ('.difyctl.install.' + [guid]::NewGuid().ToString('N') + '.exe')
try {
Copy-Item -Path $assetPath -Destination $stage -Force
Move-Item -Path $stage -Destination $targetBin -Force
}
catch {
Remove-Item -Path $stage -Force -ErrorAction SilentlyContinue
throw "cannot replace $targetBin — close any running difyctl and re-run."
}
Write-Host ""
Write-Host "difyctl v$ver installed (from Dify $difyTag): $targetBin"
if (($env:PATH -split ';') -notcontains $binDir) {
Write-Host ""
Write-Host "$binDir is not on your PATH. Add it with:"
Write-Host (Get-PathHint $binDir)
}
else {
Write-Host 'verify: run "difyctl version"'
Write-SkillHint $targetBin
}
}
finally {
Remove-Item -Recurse -Force $tmp -ErrorAction SilentlyContinue
}
}
if ($env:DIFYCTL_INSTALL_LIB -ne '1') { Invoke-Main }
@@ -0,0 +1,363 @@
import { spawnSync } from 'node:child_process'
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { describe, expect, it, vi } from 'vite-plus/test'
const SCRIPT = fileURLToPath(new URL('./install.ps1', import.meta.url))
function hasPwsh(): boolean {
const r = spawnSync(
'pwsh',
['-NoProfile', '-NonInteractive', '-Command', '$PSVersionTable.PSVersion.Major'],
{
encoding: 'utf8',
},
)
return r.status === 0
}
const PWSH = hasPwsh()
// Each test starts pwsh; cold starts on a busy CI runner can exceed the default 5 seconds.
if (PWSH) vi.setConfig({ testTimeout: 15_000 })
const STUB = [
'function Invoke-RestMethod {',
' param([string]$Uri, $Headers)',
" if ($Uri -like '*/releases/latest') {",
" if (-not $env:HX_LATEST) { throw 'mock 404' }",
' return ($env:HX_LATEST | ConvertFrom-Json)',
' }',
" elseif ($Uri -like '*/releases?per_page=100') {",
" if (-not $env:HX_LIST) { throw 'mock 404' }",
' return ($env:HX_LIST | ConvertFrom-Json)',
' }',
" elseif ($Uri -like '*/releases/tags/*') {",
" $t = $Uri -replace '.*/releases/tags/', ''",
" $k = 'HX_TAG_' + ($t -replace '[.\\-]', '_')",
' $v = [Environment]::GetEnvironmentVariable($k)',
" if (-not $v) { throw 'mock 404' }",
' return ($v | ConvertFrom-Json)',
' }',
' throw "unexpected uri $Uri"',
'}',
].join('\n')
type Run = { code: number; stdout: string; stderr: string }
function runPwsh(body: string, env: Record<string, string> = {}): Run {
const script = `$ErrorActionPreference='Stop'\n${STUB}\n. '${SCRIPT}'\n${body}`
const r = spawnSync('pwsh', ['-NoProfile', '-NonInteractive', '-Command', script], {
encoding: 'utf8',
env: {
...process.env,
DIFYCTL_INSTALL_LIB: '1',
DIFY_VERSION: '',
DIFYCTL_VERSION: '',
LOCALAPPDATA: process.env.LOCALAPPDATA || '/tmp',
TEMP: process.env.TEMP || '/tmp',
...env,
},
})
return { code: r.status ?? 1, stdout: (r.stdout ?? '').trim(), stderr: r.stderr ?? '' }
}
const REL_1142 = JSON.stringify({
tag_name: '1.14.2',
assets: [{ name: 'difyctl-v0.2.0-windows-x64.exe' }],
})
const REL_1150 = JSON.stringify({
tag_name: '1.15.0',
assets: [{ name: 'difyctl-v0.3.0-windows-x64.exe' }],
})
const LIST_NEWEST_FIRST = JSON.stringify([
{ tag_name: '1.15.0', assets: [{ name: 'difyctl-v0.3.0-windows-x64.exe' }] },
{ tag_name: '1.14.2', assets: [{ name: 'difyctl-v0.2.0-windows-x64.exe' }] },
])
describe.skipIf(!PWSH)('install.ps1 Get-AssetSemver', () => {
it('extracts the version from a windows .exe asset name', () => {
const r = runPwsh("(Get-AssetSemver 'difyctl-v0.2.0-windows-x64.exe').Version")
expect(r.code).toBe(0)
expect(r.stdout).toBe('0.2.0')
})
it('extracts a prerelease version and its rc number', () => {
const r = runPwsh(
'$a = Get-AssetSemver \'difyctl-v0.1.0-rc.1-windows-x64.exe\'; "$($a.Version) $($a.Rc)"',
)
expect(r.code).toBe(0)
expect(r.stdout).toBe('0.1.0-rc.1 1')
})
it('rejects a non-windows asset (returns null)', () => {
const r = runPwsh(
"if ($null -eq (Get-AssetSemver 'difyctl-v0.2.0-linux-x64')) { 'NULL' } else { 'OBJ' }",
)
expect(r.code).toBe(0)
expect(r.stdout).toBe('NULL')
})
it('rejects a malformed core version (returns null)', () => {
const r = runPwsh(
"if ($null -eq (Get-AssetSemver 'difyctl-vx.y.z-windows-x64.exe')) { 'NULL' } else { 'OBJ' }",
)
expect(r.code).toBe(0)
expect(r.stdout).toBe('NULL')
})
})
describe.skipIf(!PWSH)('install.ps1 Select-Asset', () => {
it('picks the highest semver among several windows builds', () => {
const rel = JSON.stringify({
assets: [
{ name: 'difyctl-v0.2.0-windows-x64.exe' },
{ name: 'difyctl-v0.10.0-windows-x64.exe' },
{ name: 'difyctl-v0.9.0-windows-x64.exe' },
],
})
const r = runPwsh(`(Select-Asset ('${rel}' | ConvertFrom-Json)).Version`)
expect(r.code).toBe(0)
expect(r.stdout).toBe('0.10.0')
})
it('prefers the stable release over an rc of the same core', () => {
const rel = JSON.stringify({
assets: [
{ name: 'difyctl-v0.2.0-rc.1-windows-x64.exe' },
{ name: 'difyctl-v0.2.0-windows-x64.exe' },
],
})
const r = runPwsh(`(Select-Asset ('${rel}' | ConvertFrom-Json)).Version`)
expect(r.code).toBe(0)
expect(r.stdout).toBe('0.2.0')
})
it('ignores checksums and non-windows assets', () => {
const rel = JSON.stringify({
assets: [
{ name: 'difyctl-v0.2.0-linux-x64' },
{ name: 'difyctl-v0.2.0-checksums.txt' },
{ name: 'difyctl-v0.2.0-windows-x64.exe' },
{ name: 'some-other-asset.zip' },
],
})
const r = runPwsh(`(Select-Asset ('${rel}' | ConvertFrom-Json)).Name`)
expect(r.code).toBe(0)
expect(r.stdout).toBe('difyctl-v0.2.0-windows-x64.exe')
})
it('yields null when no windows asset is present', () => {
const rel = JSON.stringify({ assets: [{ name: 'difyctl-v0.2.0-linux-x64' }] })
const r = runPwsh(
`if ($null -eq (Select-Asset ('${rel}' | ConvertFrom-Json))) { 'NULL' } else { 'OBJ' }`,
)
expect(r.code).toBe(0)
expect(r.stdout).toBe('NULL')
})
})
describe.skipIf(!PWSH)('install.ps1 Resolve-Release', () => {
it('DIFY_VERSION pins the release directly', () => {
const r = runPwsh('(Resolve-Release).tag_name', {
DIFY_VERSION: '1.14.2',
HX_TAG_1_14_2: REL_1142,
})
expect(r.code).toBe(0)
expect(r.stdout).toBe('1.14.2')
})
it('DIFY_VERSION that does not exist throws a clear message', () => {
const r = runPwsh('(Resolve-Release).tag_name', { DIFY_VERSION: '9.9.9' })
expect(r.code).not.toBe(0)
expect(r.stderr).toContain('Dify release 9.9.9 not found')
})
it('blank resolves to the latest release', () => {
const r = runPwsh('(Resolve-Release).tag_name', { HX_LATEST: REL_1150 })
expect(r.code).toBe(0)
expect(r.stdout).toBe('1.15.0')
})
it('blank throws when the latest query fails (no silent fallback)', () => {
const r = runPwsh('(Resolve-Release).tag_name')
expect(r.code).not.toBe(0)
expect(r.stderr).toContain('failed to query latest Dify release')
})
it('DIFYCTL_VERSION resolves to the release hosting that build', () => {
const r = runPwsh('(Resolve-Release).tag_name', {
DIFYCTL_VERSION: '0.2.0',
HX_LIST: LIST_NEWEST_FIRST,
})
expect(r.code).toBe(0)
expect(r.stdout).toBe('1.14.2')
})
it('DIFYCTL_VERSION not hosted anywhere throws', () => {
const r = runPwsh('(Resolve-Release).tag_name', {
DIFYCTL_VERSION: '9.9.9',
HX_LIST: LIST_NEWEST_FIRST,
})
expect(r.code).not.toBe(0)
expect(r.stderr).toContain('difyctl 9.9.9 not found on any Dify release')
})
})
describe.skipIf(!PWSH)('install.ps1 Find-ReleaseForDifyctl', () => {
it('returns the newest release whose assets host the wanted build', () => {
const r = runPwsh("(Find-ReleaseForDifyctl '0.2.0').tag_name", { HX_LIST: LIST_NEWEST_FIRST })
expect(r.code).toBe(0)
expect(r.stdout).toBe('1.14.2')
})
it('returns nothing when no release hosts the wanted build', () => {
const r = runPwsh(
"$x = Find-ReleaseForDifyctl '9.9.9'; if ($null -eq $x) { 'NULL' } else { $x.tag_name }",
{ HX_LIST: LIST_NEWEST_FIRST },
)
expect(r.code).toBe(0)
expect(r.stdout).toBe('NULL')
})
})
// Build a fake ErrorRecord whose Exception.Response is a real HttpResponseMessage
// carrying the given status + headers, matching what Get-RateLimitInfo inspects.
function fakeErr(status: number, headers: Record<string, string>): string {
const adds = Object.entries(headers)
.map(([k, v]) => `$resp.Headers.TryAddWithoutValidation('${k}','${v}') | Out-Null`)
.join('\n')
return [
`$resp = [System.Net.Http.HttpResponseMessage]::new([System.Net.HttpStatusCode]${status})`,
adds,
'$err = [pscustomobject]@{ Exception = [pscustomobject]@{ Response = $resp } }',
].join('\n')
}
const futureReset = String(Math.floor(Date.now() / 1000) + 1800)
describe.skipIf(!PWSH)('install.ps1 rate limit', () => {
it('classifies a 403 with x-ratelimit-remaining:0 as rate-limited, returning the reset', () => {
const r =
runPwsh(`${fakeErr(403, { 'x-ratelimit-remaining': '0', 'x-ratelimit-reset': futureReset })}
$i = Get-RateLimitInfo $err; if ($null -eq $i) { 'NULL' } else { $i.Reset }`)
expect(r.code).toBe(0)
expect(r.stdout).toBe(futureReset)
})
it('does not classify a 403 with remaining tokens as rate-limited', () => {
const r = runPwsh(`${fakeErr(403, { 'x-ratelimit-remaining': '59' })}
$i = Get-RateLimitInfo $err; if ($null -eq $i) { 'NULL' } else { 'LIMITED' }`)
expect(r.code).toBe(0)
expect(r.stdout).toBe('NULL')
})
it('always treats a 429 as rate-limited', () => {
const r = runPwsh(`${fakeErr(429, {})}
$i = Get-RateLimitInfo $err; if ($null -eq $i) { 'NULL' } else { 'LIMITED' }`)
expect(r.code).toBe(0)
expect(r.stdout).toBe('LIMITED')
})
it('returns null for an error without a response (e.g. a plain string throw)', () => {
const r = runPwsh(
"$err = [pscustomobject]@{ Exception = [pscustomobject]@{} }; if ($null -eq (Get-RateLimitInfo $err)) { 'NULL' } else { 'OBJ' }",
)
expect(r.code).toBe(0)
expect(r.stdout).toBe('NULL')
})
it('Write-RateLimitHint prints cause, ETA, and remediation to stderr', () => {
const r = runPwsh(`Write-RateLimitHint '${futureReset}'`)
expect(r.code).toBe(0)
expect(r.stderr).toContain('rate limit exceeded')
expect(r.stderr).toContain('resets in ~')
expect(r.stderr).toContain('GITHUB_TOKEN')
})
it('Write-RateLimitHint omits the ETA line when the reset epoch is missing', () => {
const r = runPwsh("Write-RateLimitHint ''")
expect(r.code).toBe(0)
expect(r.stderr).toContain('rate limit exceeded')
expect(r.stderr).not.toContain('resets in ~')
})
it('sends an Authorization header when GITHUB_TOKEN is set', () => {
const r = runPwsh('$headers.Authorization', { GITHUB_TOKEN: 'ghp_secret123' })
expect(r.code).toBe(0)
expect(r.stdout).toBe('Bearer ghp_secret123')
})
it('Resolve-Release surfaces the rate-limit hint and exits, not "not found"', () => {
const stub = `function Invoke-RestMethod { throw [Microsoft.PowerShell.Commands.HttpResponseException]::new('rate limited', $script:rlResp) }`
// The stub bypasses Invoke-RestMethod's module autoload, which provides HttpResponseException.
const setup = `Import-Module Microsoft.PowerShell.Utility
$script:rlResp = [System.Net.Http.HttpResponseMessage]::new([System.Net.HttpStatusCode]403)
$script:rlResp.Headers.TryAddWithoutValidation('x-ratelimit-remaining','0') | Out-Null
$script:rlResp.Headers.TryAddWithoutValidation('x-ratelimit-reset','${futureReset}') | Out-Null`
const r = runPwsh(`${setup}\n${stub}\nResolve-Release`, { DIFY_VERSION: '1.15.0' })
expect(r.code).toBe(1)
expect(r.stderr).toContain('rate limit exceeded')
expect(r.stderr).not.toContain('not found')
})
})
describe.skipIf(!PWSH)('install.ps1 install location and PATH hint', () => {
const where = (env: Record<string, string>) =>
runPwsh('Write-Output (Resolve-BinDir)', {
DIFYCTL_PREFIX: '',
DIFYCTL_INSTALL_DIR: '',
LOCALAPPDATA: '/lad',
...env,
}).stdout
it('defaults to %LOCALAPPDATA%\\difyctl\\bin', () => {
expect(where({})).toBe(join('/lad', 'difyctl', 'bin'))
})
it('puts the binary under <DIFYCTL_PREFIX>\\bin', () => {
expect(where({ DIFYCTL_PREFIX: '/opt/dify' })).toBe(join('/opt/dify', 'bin'))
})
it('takes DIFYCTL_INSTALL_DIR as the bin folder itself, over DIFYCTL_PREFIX', () => {
expect(where({ DIFYCTL_PREFIX: '/opt/dify', DIFYCTL_INSTALL_DIR: '/custom/bin' })).toBe(
'/custom/bin',
)
})
it('the PATH command adds to the user PATH, not the whole session PATH', () => {
const hint = runPwsh(`Write-Output (Get-PathHint 'C:\\dify\\bin')`).stdout
expect(hint).toContain(
`"C:\\dify\\bin;" + [Environment]::GetEnvironmentVariable('PATH', 'User')`,
)
expect(hint).not.toContain('$env:PATH')
})
})
// A v2 binary answers `install skills --help`; a v1 one exits 1 with "unknown command".
// The fakes are shell scripts, so this runs where pwsh runs outside Windows.
describe.skipIf(!PWSH || process.platform === 'win32')('install.ps1 Write-SkillHint', () => {
const hint = (bin: string) => runPwsh(`Write-SkillHint '${bin}'`)
it('prints the hint for a binary that has install skills, and stays quiet otherwise', () => {
const dir = mkdtempSync(join(tmpdir(), 'difyctl-hint-'))
try {
const v2 = join(dir, 'v2')
const v1 = join(dir, 'v1')
writeFileSync(v2, '#!/bin/sh\n[ "$*" = "install skills --help" ]\n', { mode: 0o755 })
writeFileSync(v1, '#!/bin/sh\necho "unknown command: $*" >&2\nexit 1\n', { mode: 0o755 })
expect(hint(v2)).toMatchObject({
code: 0,
stdout: expect.stringContaining('difyctl install skills <skills root>'),
})
expect(hint(v1)).toMatchObject({ code: 0, stdout: '' })
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
it('prints nothing when the binary cannot run', () => {
expect(hint('/nonexistent/difyctl')).toMatchObject({ code: 0, stdout: '' })
})
})
+22
View File
@@ -0,0 +1,22 @@
#!/usr/bin/env bash
# scripts/lib/common.sh — shared shell helpers for cli/ scripts.
[[ -n "${DIFYCTL_LIB_COMMON_SH:-}" ]] && return 0
readonly DIFYCTL_LIB_COMMON_SH=1
log::info() { printf '\033[36m[info]\033[0m %s\n' "$*" >&2; }
log::warn() { printf '\033[33m[warn]\033[0m %s\n' "$*" >&2; }
log::err() { printf '\033[31m[err ]\033[0m %s\n' "$*" >&2; }
die() { log::err "$*"; exit 1; }
# Resolve the cli/ directory (parent of scripts/).
cli::root() {
local dir
dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
printf '%s' "$dir"
}
require() {
command -v "$1" >/dev/null 2>&1 || die "missing dependency: $1${2:+ — $2}"
}
@@ -0,0 +1,77 @@
import type { ExecSyncOptions } from 'node:child_process'
import { execSync } from 'node:child_process'
import { readFileSync } from 'node:fs'
import { dirname, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
export const BUILD_CHANNELS = ['dev', 'alpha', 'rc', 'edge', 'stable'] as const
export type BuildChannel = (typeof BUILD_CHANNELS)[number]
export type BuildInfo = {
version: string
commit: string
buildDate: string
channel: BuildChannel
}
export type Env = Record<string, string | undefined>
export type GitProbe = (cmd: string) => string | null
const GIT_PROBE_OPTS: ExecSyncOptions = {
stdio: ['ignore', 'pipe', 'ignore'],
}
export const defaultGitProbe: GitProbe = (cmd) => {
try {
return execSync(cmd, GIT_PROBE_OPTS).toString().trim() || null
} catch {
return null
}
}
type PackageManifest = {
difyctl?: {
channel?: string
}
}
export type PackageReader = () => PackageManifest
// Default reader resolves cli/package.json relative to this file so the same
// helper works whether invoked from vite.config.ts, bin/dev.js, or release.sh.
const defaultPackageReader: PackageReader = () => {
try {
const pkgPath = resolve(dirname(fileURLToPath(import.meta.url)), '..', '..', 'package.json')
return JSON.parse(readFileSync(pkgPath, 'utf8')) as PackageManifest
} catch {
return {}
}
}
export type ResolveOptions = {
env?: Env
git?: GitProbe
now?: () => Date
pkg?: PackageReader
}
export function resolveBuildInfo(opts: ResolveOptions = {}): BuildInfo {
const env = opts.env ?? process.env
const git = opts.git ?? defaultGitProbe
const now = opts.now ?? (() => new Date())
const pkg = (opts.pkg ?? defaultPackageReader)()
const channel = env.DIFYCTL_CHANNEL ?? pkg.difyctl?.channel ?? 'dev'
if (!(BUILD_CHANNELS as readonly string[]).includes(channel)) {
throw new Error(`invalid DIFYCTL_CHANNEL: ${channel} (expected ${BUILD_CHANNELS.join(' | ')})`)
}
const version = env.DIFYCTL_VERSION ?? git('git describe --tags --dirty --always') ?? '0.0.0-dev'
const commit = env.DIFYCTL_COMMIT ?? git('git rev-parse HEAD') ?? 'none'
const buildDate = env.DIFYCTL_BUILD_DATE ?? now().toISOString()
return { version, commit, buildDate, channel: channel as BuildChannel }
}
@@ -0,0 +1,9 @@
import { resolveBuildInfo } from './lib/resolve-buildinfo.js'
const info = resolveBuildInfo()
process.stdout.write(
`version: ${info.version}\n` +
`commit: ${info.commit}\n` +
`built: ${info.buildDate}\n` +
`channel: ${info.channel}\n`,
)
+80
View File
@@ -0,0 +1,80 @@
#!/usr/bin/env bash
# scripts/release-build.sh — cross-compile difyctl to standalone binaries
# for every release target via `bun build --compile`.
#
# Bun consumes bin/run.ts (which imports from src/) directly — no `pnpm build`
# / dist/ step needed.
#
# Prereqs:
# - All @napi-rs/keyring native variants present in node_modules. Append
# cli/scripts/cross-arch.pnpm.yaml onto pnpm-workspace.yaml before the
# install that first populates node_modules so pnpm fetches every
# foreign-arch prebuild (the CLI Release workflow does this).
#
# Env (all optional; defaults derived from cli/package.json + git):
# CLI_VERSION — package.json `version`
# DIFYCTL_CHANNEL — package.json `difyctl.channel`
# DIFYCTL_COMMIT — `git rev-parse HEAD` (or "unknown")
# DIFYCTL_BUILD_DATE — current UTC time
#
# Output: dist/bin/difyctl-v<CLI_VERSION>-<target>[.exe]
set -euo pipefail
_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=lib/common.sh
source "${_dir}/lib/common.sh"
require bun
cli_root="$(cli::root)"
entry="${cli_root}/bin/run.ts"
out_dir="${cli_root}/dist/bin"
read_pkg() { node -p "require('${cli_root}/package.json').$1" 2>/dev/null; }
naming() { node "${_dir}/release-naming.mjs" "$@"; }
CLI_VERSION="${CLI_VERSION:-$(read_pkg version)}"
DIFYCTL_CHANNEL="${DIFYCTL_CHANNEL:-$(read_pkg difyctl.channel)}"
DIFYCTL_COMMIT="${DIFYCTL_COMMIT:-$(git -C "$cli_root" rev-parse HEAD 2>/dev/null || echo unknown)}"
DIFYCTL_BUILD_DATE="${DIFYCTL_BUILD_DATE:-$(date -u +%Y-%m-%dT%H:%M:%SZ)}"
[[ "$CLI_VERSION" != "undefined" ]] || die "CLI_VERSION could not be derived from package.json"
repo_root="$(cd "${cli_root}/.." && pwd)"
skill_dir="${repo_root}/skills/difyctl"
[[ -f "${skill_dir}/SKILL.md" ]] || die "skill not found: ${skill_dir}"
[[ -f "$entry" ]] || die "entry not found: $entry"
rm -rf "$out_dir"
mkdir -p "$out_dir"
# Build-info globals (referenced as bare identifiers in src/version/info.ts).
# Each value must be a JS expression — wrap strings as JSON-quoted strings.
defines=(
"--define" "__DIFYCTL_VERSION__=\"${CLI_VERSION}\""
"--define" "__DIFYCTL_CHANNEL__=\"${DIFYCTL_CHANNEL}\""
"--define" "__DIFYCTL_COMMIT__=\"${DIFYCTL_COMMIT}\""
"--define" "__DIFYCTL_BUILD_DATE__=\"${DIFYCTL_BUILD_DATE}\""
"--define" "__DIFYCTL_COMPILED__=true"
)
# Targets and asset names come from cli/package.json `difyctl.release` via
# release-naming.mjs (single source of truth). Each line: bunTarget<TAB>id<TAB>exe.
while IFS=$'\t' read -r bun_target asset_target _exe; do
out="${out_dir}/$(naming asset "$CLI_VERSION" "$asset_target")"
log::info "compiling ${asset_target} -> $(basename "$out")..."
# Run from the repo root: --asset paths are embedded relative to the cwd, which gives
# the skill its difyctl/ prefix.
(cd "$repo_root" && bun build "$entry" \
--asset "$skill_dir" \
--target="$bun_target" \
--compile \
--minify \
"${defines[@]}" \
--outfile="$out") >/dev/null
done < <(naming targets)
log::info "built $(find "$out_dir" -type f | wc -l | tr -d ' ') binaries:"
ls -lh "$out_dir" >&2
@@ -0,0 +1,211 @@
#!/usr/bin/env node
// release-naming.mjs — single source of truth for difyctl release artifact
// names and version/channel rules. Reads DATA from cli/package.json
// `difyctl.release` (plus `version` and `difyctl.channel`) and owns the name
// FORMAT and the per-channel version form. Producer scripts call this;
// `validate` is the release gate.
//
// Subcommands:
// tag <version> -> <tagPrefix><version>
// asset <version> <id> -> <tagPrefix><version>-<id>[.exe]
// checksums <version> -> <tagPrefix><version><checksumsSuffix>
// tag-prefix -> <tagPrefix>
// targets -> one line per target: "<bunTarget>\t<id>\t<0|1 exe>"
// channels -> one channel name per line
// prerelease <channel> -> "true" | "false"
// github-env -> key=value lines (all fields CI needs) for $GITHUB_ENV
// edge-version <sha> -> <package version core>-edge.<sha>
// validate -> exit 1 if difyctl.release, version, or channel is malformed
// validate-version <version> <channel>
// -> exit 1 unless version matches the channel's form
import { readFileSync, realpathSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
const BUN_TARGET_RE = /^bun-(linux|darwin|windows)-(x64|arm64)$/
const SEMVER_CORE_RE = /^\d+\.\d+\.\d+$/
// Add channels here: { name, prerelease, versionForm }.
const CHANNELS = [
{ name: 'stable', prerelease: false, versionForm: /^\d+\.\d+\.\d+(\+[0-9A-Z.-]+)?$/i },
{ name: 'alpha', prerelease: true, versionForm: /^\d+\.\d+\.\d+-alpha(\.\d+)?$/ },
{ name: 'rc', prerelease: true, versionForm: /^\d+\.\d+\.\d+-rc\.\d+$/ },
{ name: 'edge', prerelease: true, versionForm: /^\d+\.\d+\.\d+-edge\.[0-9a-f]{7,40}$/ },
]
const channelByName = (name) => CHANNELS.find((c) => c.name === name)
const channelNames = () => CHANNELS.map((c) => c.name).join(', ')
function versionCore(v) {
return String(v).replace(/^v/, '').replace(/\+.*$/, '').split('-')[0]
}
function edgeVersion(sha) {
if (!/^[0-9a-f]{7,40}$/.test(sha ?? ''))
die('edge-version requires a git short sha (7-40 hex chars)')
const { version } = loadPkg()
const core = versionCore(version)
if (!SEMVER_CORE_RE.test(core)) die(`cannot derive edge base from version: ${version}`)
return `${core}-edge.${sha}`
}
// Returns a problem string if `version` cannot be resolved under `channel`, else
// null. Shared by validateVersionForChannel (die-now) and validateVersionChannel
// (collect for the `validate` gate).
function channelVersionProblem(version, channel) {
if (typeof version !== 'string' || version.length === 0)
return 'version must be a non-empty string'
const ch = channelByName(channel)
if (!ch) return `unknown channel: ${channel} (expected one of: ${channelNames()})`
if (!ch.versionForm.test(version))
return `version ${version} does not match the ${channel} channel form`
return null
}
function validateVersionForChannel(version, channelName) {
const problem = channelVersionProblem(version, channelName)
if (problem) die(problem)
return `valid: ${version} is a ${channelName} version`
}
function die(msg) {
process.stderr.write(`release-naming: ${msg}\n`)
process.exit(1)
}
// Tests point this at a fixture manifest so their assertions stay fixed while
// the real version moves with every release. The name is mirrored in
// test/fixtures/pkg-manifest.ts rather than imported from here, because this
// file's shebang breaks the Windows test runner.
const PKG_PATH_ENV = 'DIFYCTL_PKG_PATH'
function loadPkg() {
const pkgPath = process.env[PKG_PATH_ENV] || new URL('../package.json', import.meta.url)
const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'))
if (!pkg.difyctl?.release) die('cli/package.json missing difyctl.release')
return {
version: pkg.version,
channel: pkg.difyctl.channel,
release: pkg.difyctl.release,
}
}
// Emits key=value lines for $GITHUB_ENV.
function githubEnv() {
const { version, channel, release } = loadPkg()
const fields = {
version,
channel,
prerelease: channelByName(channel)?.prerelease ?? false,
tagPrefix: release.tagPrefix,
difyctlTag: `${release.tagPrefix}${version}`,
}
return Object.entries(fields)
.map(([k, v]) => `${k}=${v}`)
.join('\n')
}
function requireVersion(version) {
if (!version) die('version argument is required')
return version
}
function assetName(release, version, id) {
const target = release.targets.find((t) => t.id === id)
if (!target) die(`unknown target id: ${id}`)
const suffix = target.exe ? '.exe' : ''
return `${release.tagPrefix}${version}-${id}${suffix}`
}
function validateRelease(release) {
const problems = []
const str = (v) => typeof v === 'string' && v.length > 0
if (!str(release.tagPrefix)) problems.push('tagPrefix must be a non-empty string')
if (!str(release.binName)) problems.push('binName must be a non-empty string')
if (!str(release.checksumsSuffix)) problems.push('checksumsSuffix must be a non-empty string')
if (!Array.isArray(release.targets) || release.targets.length === 0) {
problems.push('targets must be a non-empty array')
return problems
}
const seen = new Set()
for (const t of release.targets) {
const label = t?.id ?? JSON.stringify(t)
if (!str(t?.id)) problems.push(`target ${label}: id must be a non-empty string`)
else if (seen.has(t.id)) problems.push(`duplicate target id: ${t.id}`)
else seen.add(t.id)
if (!str(t?.bunTarget) || !BUN_TARGET_RE.test(t.bunTarget))
problems.push(`target ${label}: bunTarget must match ${BUN_TARGET_RE}`)
if (typeof t?.exe !== 'boolean') problems.push(`target ${label}: exe must be a boolean`)
else if (str(t?.bunTarget) && t.exe !== t.bunTarget.startsWith('bun-windows-'))
problems.push(`target ${label}: exe must be true iff bunTarget is bun-windows-*`)
}
return problems
}
function validateVersionChannel(version, channel) {
const problem = channelVersionProblem(version, channel)
return problem ? [problem] : []
}
function main(argv) {
const [cmd, ...rest] = argv
switch (cmd) {
case 'tag':
return `${loadPkg().release.tagPrefix}${requireVersion(rest[0])}`
case 'asset':
return assetName(
loadPkg().release,
requireVersion(rest[0]),
rest[1] ?? die('target id is required'),
)
case 'checksums': {
const { release } = loadPkg()
return `${release.tagPrefix}${requireVersion(rest[0])}${release.checksumsSuffix}`
}
case 'tag-prefix':
return loadPkg().release.tagPrefix
case 'targets':
return loadPkg()
.release.targets.map((t) => `${t.bunTarget}\t${t.id}\t${t.exe ? 1 : 0}`)
.join('\n')
case 'channels':
return CHANNELS.map((c) => c.name).join('\n')
case 'github-env':
return githubEnv()
case 'prerelease': {
const ch = channelByName(rest[0] ?? die('channel argument is required'))
if (!ch) die(`unknown channel: ${rest[0]} (expected one of: ${channelNames()})`)
return String(ch.prerelease)
}
case 'validate': {
const { version, channel, release } = loadPkg()
const problems = [...validateRelease(release), ...validateVersionChannel(version, channel)]
if (problems.length > 0)
die(`invalid difyctl release config:\n - ${problems.join('\n - ')}`)
return `difyctl release valid: version=${version} channel=${channel} targets=${release.targets.length}`
}
case 'edge-version':
return edgeVersion(rest[0])
case 'validate-version':
return validateVersionForChannel(
requireVersion(rest[0]),
rest[1] ?? die('channel argument is required'),
)
default:
die(`unknown subcommand: ${cmd ?? '(none)'}`)
}
}
const invokedDirectly =
process.argv[1] && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)
if (invokedDirectly) process.stdout.write(`${main(process.argv.slice(2))}\n`)
export {
assetName,
channelByName,
CHANNELS,
edgeVersion,
loadPkg,
validateVersionForChannel,
versionCore,
}
@@ -0,0 +1,146 @@
import type { PkgManifestOverrides } from '../test/fixtures/pkg-manifest'
import { execFileSync } from 'node:child_process'
import { readFileSync, writeFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { describe, expect, it } from 'vite-plus/test'
import {
FIXTURE_CHANNEL,
FIXTURE_TAG_PREFIX,
FIXTURE_VERSION,
pkgManifestEnv,
} from '../test/fixtures/pkg-manifest'
const SCRIPT = fileURLToPath(new URL('./release-naming.mjs', import.meta.url))
const PKG_ENV = pkgManifestEnv()
type RunResult = { code: number; stdout: string; stderr: string }
function exec(args: string[], pkgEnv: Record<string, string>): RunResult {
try {
const stdout = execFileSync('node', [SCRIPT, ...args], {
encoding: 'utf8',
env: { ...process.env, ...pkgEnv },
})
return { code: 0, stdout, stderr: '' }
} catch (e) {
const err = e as { status?: number; stdout?: string; stderr?: string }
return { code: err.status ?? 1, stdout: err.stdout ?? '', stderr: err.stderr ?? '' }
}
}
function run(args: string[]): RunResult {
return exec(args, PKG_ENV)
}
function runWith(overrides: PkgManifestOverrides, args: string[]): RunResult {
return exec(args, pkgManifestEnv(overrides))
}
type FixtureManifest = {
version?: string
difyctl: { channel?: string }
}
function runOnManifest(mutate: (manifest: FixtureManifest) => void, args: string[]): RunResult {
const pkgEnv = pkgManifestEnv()
const [pkgPath] = Object.values(pkgEnv)
if (!pkgPath) throw new Error('pkgManifestEnv returned no manifest path')
const manifest = JSON.parse(readFileSync(pkgPath, 'utf8')) as FixtureManifest
mutate(manifest)
writeFileSync(pkgPath, JSON.stringify(manifest))
return exec(args, pkgEnv)
}
function parseKeyValues(stdout: string): Record<string, string> {
return Object.fromEntries(
stdout
.split('\n')
.filter(Boolean)
.map((line) => [line.slice(0, line.indexOf('=')), line.slice(line.indexOf('=') + 1)]),
)
}
describe('release-naming github-env', () => {
it('emits every manifest field for $GITHUB_ENV, plus a composed difyctlTag', () => {
const fields = parseKeyValues(run(['github-env']).stdout)
expect(fields).toEqual({
version: FIXTURE_VERSION,
channel: FIXTURE_CHANNEL,
prerelease: 'false',
tagPrefix: FIXTURE_TAG_PREFIX,
difyctlTag: `${FIXTURE_TAG_PREFIX}${FIXTURE_VERSION}`,
})
})
})
describe('release-naming edge channel', () => {
it('edge-version derives <version core>-edge.<sha> from the package version', () => {
expect(run(['edge-version', '2fd7b82']).stdout.trim()).toBe(`${FIXTURE_VERSION}-edge.2fd7b82`)
})
it('edge-version accepts a 40-char sha', () => {
const sha = '2fd7b829e1f0aaaabbbbccccddddeeeeffff0000'
expect(run(['edge-version', sha]).stdout.trim()).toBe(`${FIXTURE_VERSION}-edge.${sha}`)
})
it('edge-version rejects a non-hex sha', () => {
expect(run(['edge-version', 'nothex!']).code).not.toBe(0)
})
it('edge-version fails when the manifest carries no version', () => {
const { code, stderr } = runOnManifest(
(m) => {
delete m.version
},
['edge-version', '2fd7b82'],
)
expect(code).not.toBe(0)
expect(stderr).toContain('cannot derive edge base from version')
})
it('validate-version rejects an rc string under the edge channel', () => {
expect(run(['validate-version', '0.1.0-rc.1', 'edge']).code).not.toBe(0)
})
})
describe('release-naming validate channel', () => {
const validateChannel = (channel: string) => runWith({ channel }, ['validate'])
it.each<[string, string]>([
['stable', FIXTURE_VERSION],
['alpha', `${FIXTURE_VERSION}-alpha`],
['rc', `${FIXTURE_VERSION}-rc.1`],
['edge', `${FIXTURE_VERSION}-edge.2fd7b82`],
])('accepts the %s channel with a version in its form', (channel, version) => {
expect(runWith({ channel, version }, ['validate']).code).toBe(0)
})
it('rejects a typo of a real channel and names it', () => {
const { code, stderr } = validateChannel('stabel')
expect(code).not.toBe(0)
expect(stderr).toContain('unknown channel: stabel')
})
it('rejects a manifest with no channel at all', () => {
const { code, stderr } = runOnManifest(
(m) => {
delete m.difyctl.channel
},
['validate'],
)
expect(code).not.toBe(0)
expect(stderr).toContain('unknown channel')
})
})
describe('release-naming validate-version', () => {
it('accepts build metadata on a stable version', () => {
expect(run(['validate-version', '1.16.1+r2', 'stable']).code).toBe(0)
})
it('accepts an alpha version under the alpha channel, with or without a counter', () => {
expect(run(['validate-version', '1.16.1-alpha', 'alpha']).code).toBe(0)
expect(run(['validate-version', '1.16.1-alpha.2', 'alpha']).code).toBe(0)
})
})
@@ -0,0 +1,130 @@
#!/usr/bin/env node
// release-r2-edge.mjs — edge/R2 release metadata generator. Two subcommands:
// manifest -> the per-channel pointer manifest.json (the installer reads this)
// index -> the per-channel build-history ledger index.json
import { existsSync, readFileSync } from 'node:fs'
import { assetName, loadPkg, validateVersionForChannel } from './release-naming.mjs'
function die(msg) {
process.stderr.write(`release-r2-edge: ${msg}\n`)
process.exit(1)
}
function parseArgs(argv) {
const out = {}
for (let i = 0; i < argv.length; i += 2) {
const key = argv[i]?.replace(/^--/, '')
const val = argv[i + 1]
if (!key || val === undefined || val.startsWith('--'))
die(`malformed argument near ${argv[i]} (expected --key value)`)
out[key] = val
}
return out
}
function requireArgs(args, keys) {
for (const k of keys) {
if (!args[k]) die(`missing --${k}`)
}
}
// checksums lines are "<sha256> <assetName>"
function shaMap(checksumsPath) {
const map = new Map()
for (const line of readFileSync(checksumsPath, 'utf8').split('\n')) {
const m = line.match(/^([0-9a-f]{64})\s+(\S+)$/i)
if (m) map.set(m[2], m[1])
}
return map
}
function emitManifest(args) {
requireArgs(args, ['channel', 'version', 'commit', 'build-date', 'base-url', 'checksums'])
validateVersionForChannel(args.version, args.channel)
const { release } = loadPkg()
const shas = shaMap(args.checksums)
const targetLines = release.targets
.map((t) => {
const asset = assetName(release, args.version, t.id)
const sha = shas.get(asset)
if (!sha) die(`no sha256 for ${asset} in ${args.checksums}`)
// one target per line: install-r2.sh grep/sed depends on this layout
return ` ${JSON.stringify(t.id)}: { "asset": ${JSON.stringify(asset)}, "sha256": ${JSON.stringify(sha)} }`
})
.join(',\n')
const head = {
schema: 1,
name: release.binName,
channel: args.channel,
version: args.version,
commit: args.commit,
buildDate: args['build-date'],
baseUrl: args['base-url'],
}
const headLines = Object.entries(head)
.map(([k, v]) => ` ${JSON.stringify(k)}: ${JSON.stringify(v)}`)
.join(',\n')
process.stdout.write(`{\n${headLines},\n "targets": {\n${targetLines}\n }\n}\n`)
}
// Newline-delimited dir names of binaries that still exist in R2. Absent file =
// no reconciliation (caller could not list); empty file = no survivors.
function loadExistingDirs(path) {
if (!path || !existsSync(path)) return null
const set = new Set()
for (const line of readFileSync(path, 'utf8').split('\n')) {
const d = line.trim()
if (d) set.add(d)
}
return set
}
function emitIndex(args) {
requireArgs(args, ['current', 'channel', 'version', 'commit', 'build-date'])
// empty / "-" / missing = no ledger yet (first publish)
let current = { schema: 1, channel: args.channel, builds: [] }
if (args.current !== '-' && existsSync(args.current)) {
const raw = readFileSync(args.current, 'utf8').trim()
if (raw && raw !== '-') {
try {
current = JSON.parse(raw)
} catch {
die(`current index at ${args.current} is not valid JSON`)
}
}
}
const entry = {
version: args.version,
commit: args.commit,
buildDate: args['build-date'],
dir: args.version,
}
const kept = (current.builds ?? []).filter((b) => b.version !== entry.version)
let builds = [entry, ...kept]
// Reconcile to binaries that still exist in R2: lifecycle/TTL on the bin prefix
// is the only deletion mechanism, so the ledger never advertises a build whose
// binary is gone. The new build is always kept (just uploaded). No count cap.
const existing = loadExistingDirs(args['existing-dirs'])
if (existing) builds = builds.filter((b) => b.dir === entry.dir || existing.has(b.dir))
const index = { schema: 1, channel: args.channel, updated: args['build-date'], builds }
process.stdout.write(`${JSON.stringify(index, null, 2)}\n`)
}
const [cmd, ...rest] = process.argv.slice(2)
const args = parseArgs(rest)
switch (cmd) {
case 'manifest':
emitManifest(args)
break
case 'index':
emitIndex(args)
break
default:
die(`unknown subcommand: ${cmd ?? '(none)'} (expected: manifest | index)`)
}
@@ -0,0 +1,311 @@
import { execFileSync, spawnSync } from 'node:child_process'
import { mkdtempSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { describe, expect, it } from 'vite-plus/test'
import { FIXTURE_TARGET_IDS, pkgManifestEnv } from '../test/fixtures/pkg-manifest'
const SCRIPT = fileURLToPath(new URL('./release-r2-edge.mjs', import.meta.url))
const PKG_ENV = pkgManifestEnv()
function run(args: string[]): { code: number; stdout: string; stderr: string } {
try {
return {
code: 0,
stdout: execFileSync('node', [SCRIPT, ...args], {
encoding: 'utf8',
env: { ...process.env, ...PKG_ENV },
}),
stderr: '',
}
} catch (e) {
const err = e as { status?: number; stdout?: string; stderr?: string }
return { code: err.status ?? 1, stdout: err.stdout ?? '', stderr: err.stderr ?? '' }
}
}
// ---- manifest ----
function writeChecksums(version: string): string {
const dir = mkdtempSync(join(tmpdir(), 'difyctl-manifest-'))
const lines = FIXTURE_TARGET_IDS.map((id, i) => {
const exe = id === 'windows-x64' ? '.exe' : ''
const sha = String(i).repeat(64)
return `${sha} difyctl-v${version}-${id}${exe}`
})
const file = join(dir, `difyctl-v${version}-checksums.txt`)
writeFileSync(file, `${lines.join('\n')}\n`)
return file
}
const VERSION = '0.1.0-edge.2fd7b82'
const BASE_URL = 'https://example.r2.dev/difyctl/edge/0.1.0-edge.2fd7b82'
type ManifestJson = {
schema: number
name: string
channel: string
version: string
commit: string
buildDate: string
baseUrl: string
targets: Record<(typeof FIXTURE_TARGET_IDS)[number], { asset: string; sha256: string }>
}
type IndexBuild = {
version: string
commit: string
buildDate: string
dir: string
}
type IndexJson = {
schema: number
channel: string
updated: string
builds: IndexBuild[]
}
function buildManifest(version = VERSION): {
code: number
json: ManifestJson
stdout: string
stderr: string
} {
const checksums = writeChecksums(version)
const r = run([
'manifest',
'--channel',
'edge',
'--version',
version,
'--commit',
'abc1234',
'--build-date',
'2026-06-14T12:00:00Z',
'--base-url',
BASE_URL,
'--checksums',
checksums,
])
return {
code: r.code,
json: (r.code === 0 ? JSON.parse(r.stdout) : null) as ManifestJson,
stdout: r.stdout,
stderr: r.stderr,
}
}
describe('release-r2-edge manifest', () => {
it('emits the core pointer fields', () => {
const { json } = buildManifest()
expect(json.schema).toBe(1)
expect(json.name).toBe('difyctl')
expect(json.channel).toBe('edge')
expect(json.version).toBe(VERSION)
expect(json.commit).toBe('abc1234')
expect(json.buildDate).toBe('2026-06-14T12:00:00Z')
expect(json.baseUrl).toBe(BASE_URL)
})
it('lists all 5 targets with asset name + sha256 from the checksums file', () => {
const { json } = buildManifest()
expect(Object.keys(json.targets).sort()).toEqual([
'darwin-arm64',
'darwin-x64',
'linux-arm64',
'linux-x64',
'windows-x64',
])
expect(json.targets['linux-x64'].asset).toBe(`difyctl-v${VERSION}-linux-x64`)
expect(json.targets['windows-x64'].asset).toBe(`difyctl-v${VERSION}-windows-x64.exe`)
expect(json.targets['linux-x64'].sha256).toMatch(/^\d{64}$/)
})
it('renders each target on a single line (installer greps it)', () => {
const { stdout } = buildManifest()
expect(stdout).toMatch(/^ {4}"linux-x64": \{ "asset": ".*", "sha256": ".*" \}/m)
})
it('rejects a version that does not match the channel form', () => {
const { code } = buildManifest('0.1.0-rc.1')
expect(code).not.toBe(0)
})
it('dies when a target sha is missing from the checksums file', () => {
const dir = mkdtempSync(join(tmpdir(), 'difyctl-manifest-'))
const file = join(dir, `difyctl-v${VERSION}-checksums.txt`)
writeFileSync(file, `${'0'.repeat(64)} difyctl-v${VERSION}-linux-x64\n`) // only 1 of 5
const r = run([
'manifest',
'--channel',
'edge',
'--version',
VERSION,
'--commit',
'abc1234',
'--build-date',
'2026-06-14T12:00:00Z',
'--base-url',
BASE_URL,
'--checksums',
file,
])
expect(r.code).not.toBe(0)
})
it('rejects a malformed dropped-value argument (no silent misparse)', () => {
// --version has no value; --commit must NOT be swallowed as the version
const r = run([
'manifest',
'--channel',
'edge',
'--version',
'--commit',
'abc1234',
'--build-date',
'2026-06-14T12:00:00Z',
'--base-url',
'https://x',
'--checksums',
'/nonexistent',
])
expect(r.code).not.toBe(0)
})
})
// ---- index ----
function runIndex(
currentContent: string | null,
build: Omit<IndexBuild, 'dir'>,
existingDirs?: string[],
) {
let currentArg = '-'
if (currentContent !== null) {
const dir = mkdtempSync(join(tmpdir(), 'difyctl-index-'))
currentArg = join(dir, 'index.json')
writeFileSync(currentArg, currentContent)
}
const extra: string[] = []
if (existingDirs !== undefined) {
const dir = mkdtempSync(join(tmpdir(), 'difyctl-existing-'))
const f = join(dir, 'existing.txt')
writeFileSync(f, `${existingDirs.join('\n')}\n`)
extra.push('--existing-dirs', f)
}
const r = spawnSync(
'node',
[
SCRIPT,
'index',
'--current',
currentArg,
'--channel',
'edge',
'--version',
build.version,
'--commit',
build.commit,
'--build-date',
build.buildDate,
...extra,
],
{ encoding: 'utf8' },
)
return {
code: r.status ?? 1,
index: (r.status === 0 ? JSON.parse(r.stdout) : null) as IndexJson,
}
}
const B1 = { version: '0.1.0-edge.aaaaaaa', commit: 'aaaaaaa', buildDate: '2026-06-14T09:00:00Z' }
const B2 = { version: '0.1.0-edge.bbbbbbb', commit: 'bbbbbbb', buildDate: '2026-06-14T10:00:00Z' }
describe('release-r2-edge index', () => {
it('creates a fresh index from a missing current (arg "-")', () => {
const { index } = runIndex(null, B1)
expect(index.schema).toBe(1)
expect(index.channel).toBe('edge')
expect(index.builds).toHaveLength(1)
expect(index.builds[0]).toMatchObject({
version: B1.version,
commit: B1.commit,
dir: B1.version,
})
})
it('treats an empty current file as fresh (first publish, curl wrote nothing)', () => {
const { code, index } = runIndex('', B1)
expect(code).toBe(0)
expect(index.builds).toHaveLength(1)
})
it('treats a "-"-content current file as fresh (curl 404 fallback)', () => {
const { code, index } = runIndex('-\n', B1)
expect(code).toBe(0)
expect(index.builds).toHaveLength(1)
})
it('prepends the new build (publish order; newest at [0])', () => {
const current = JSON.stringify({
schema: 1,
channel: 'edge',
builds: [
{ version: B1.version, commit: B1.commit, buildDate: B1.buildDate, dir: B1.version },
],
})
const { index } = runIndex(current, B2)
expect(index.builds.map((b) => b.version)).toEqual([B2.version, B1.version])
})
it('dedups a re-cut of the same version (no duplicate, moves to top)', () => {
const current = JSON.stringify({
schema: 1,
channel: 'edge',
builds: [
{ version: B2.version, commit: B2.commit, buildDate: B2.buildDate, dir: B2.version },
{ version: B1.version, commit: B1.commit, buildDate: B1.buildDate, dir: B1.version },
],
})
const { index } = runIndex(current, B1) // re-cut B1
expect(index.builds.map((b) => b.version)).toEqual([B1.version, B2.version])
})
it('reconciles to surviving binary dirs (drops a build whose binary expired)', () => {
const current = JSON.stringify({
schema: 1,
channel: 'edge',
builds: [
{ version: B1.version, commit: B1.commit, buildDate: B1.buildDate, dir: B1.version },
],
})
// B1's binary is gone (not in existing); the new B2 is always kept.
const { index } = runIndex(current, B2, [B2.version])
expect(index.builds.map((b) => b.version)).toEqual([B2.version])
})
it('keeps the new build even when it is absent from the existing-dirs list', () => {
const { index } = runIndex(null, B1, []) // empty survivors, fresh ledger
expect(index.builds.map((b) => b.version)).toEqual([B1.version])
})
it('does not reconcile when no --existing-dirs is given (list unavailable)', () => {
const current = JSON.stringify({
schema: 1,
channel: 'edge',
builds: [
{ version: B1.version, commit: B1.commit, buildDate: B1.buildDate, dir: B1.version },
],
})
const { index } = runIndex(current, B2) // no existing-dirs → keep all
expect(index.builds.map((b) => b.version)).toEqual([B2.version, B1.version])
})
it('dies on a non-empty current file that is not valid JSON', () => {
const { code } = runIndex('{not json', B1)
expect(code).not.toBe(0)
})
})
+97
View File
@@ -0,0 +1,97 @@
#!/usr/bin/env bash
# release-r2-publish.sh — direct-publish difyctl binaries + manifest + index to R2.
# Strict order so the pointer never references missing bytes:
# sync binaries -> HEAD-verify -> list survivors -> put index.json -> put manifest.json.
# Binaries live under the bin prefix and expire via an R2 lifecycle (TTL) rule on
# that prefix; the ledger is reconciled to surviving dirs, not pruned here. The
# pointer JSONs (manifest.json/index.json) live under the (non-expiring) prefix.
# Installers (install-r2.sh/.ps1) are served from the GitHub repo, not R2.
# Usage: release-r2-publish.sh <channel> <version>
# Env: DIFYCTL_R2_S3_ENDPOINT DIFYCTL_R2_BUCKET DIFYCTL_R2_PUBLIC_BASE (+ AWS creds, AWS_REQUEST_CHECKSUM_CALCULATION).
# DIFYCTL_R2_PREFIX (default difyctl) key root for pointer JSONs
# DIFYCTL_R2_BIN_PREFIX (default <prefix>/bin) key root for binaries (TTL target)
set -euo pipefail
_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
DIST_DIR="${DIST_DIR:-${_dir}/../dist/bin}"
aws_s3() { aws --endpoint-url "$DIFYCTL_R2_S3_ENDPOINT" "$@"; }
publish_main() {
local channel="$1" version="$2"
local prefix="${DIFYCTL_R2_PREFIX:-difyctl}"
local bin_prefix="${DIFYCTL_R2_BIN_PREFIX:-${prefix}/bin}"
local key="${bin_prefix}/${channel}/${version}"
local pointer_prefix="${prefix}/${channel}"
local base_url="${DIFYCTL_R2_PUBLIC_BASE}/${key}"
local current="" new_index="" existing_dirs="" manifest=""
trap 'rm -f "$current" "$new_index" "$existing_dirs" "$manifest"' RETURN
# 1. binaries (+ checksums) — immutable
aws_s3 s3 sync "$DIST_DIR" "s3://${DIFYCTL_R2_BUCKET}/${key}/" \
--content-type application/octet-stream \
--cache-control "public, max-age=31536000, immutable"
# 2. HEAD-verify each expected target asset exists on R2. Capture targets into
# a variable first; a process-substitution producer failure bypasses set -e.
local targets
targets="$(node "${_dir}/release-naming.mjs" targets)"
[ -n "$targets" ] || { echo "release-r2-publish: no release targets resolved" >&2; exit 1; }
local verified=0 _bun id _exe asset
while IFS=$'\t' read -r _bun id _exe; do
asset="$(node "${_dir}/release-naming.mjs" asset "$version" "$id")"
aws_s3 s3api head-object --bucket "$DIFYCTL_R2_BUCKET" --key "${key}/${asset}" >/dev/null
verified=$((verified + 1))
done <<< "$targets"
[ "$verified" -gt 0 ] || { echo "release-r2-publish: verified zero targets" >&2; exit 1; }
# 3. survivors: binary dirs still present under the bin prefix (lifecycle/TTL may
# have deleted old ones). aws CLI auto-paginates list-objects-v2, so --query
# aggregates CommonPrefixes across all pages. On a list failure, skip
# reconciliation (keep the ledger as-is) rather than wrongly drop builds.
existing_dirs="$(mktemp)"
local listed=0 raw
raw="$(mktemp)"
if aws_s3 s3api list-objects-v2 --bucket "$DIFYCTL_R2_BUCKET" \
--prefix "${bin_prefix}/${channel}/" --delimiter / \
--query 'CommonPrefixes[].Prefix' --output text > "$raw" 2>/dev/null; then
# text rows are "<bin_prefix>/<channel>/<dir>/"; emit just <dir>. "None" = empty.
tr '\t' '\n' < "$raw" | awk -F/ 'NF>1 && $0 != "None" { print $(NF-1) }' > "$existing_dirs"
listed=1
fi
rm -f "$raw"
# 4. index.json: fetch current, prepend, reconcile to survivors.
current="$(mktemp)"
curl -fsSL "${DIFYCTL_R2_PUBLIC_BASE}/${pointer_prefix}/index.json" -o "$current" 2>/dev/null || echo '-' > "$current"
new_index="$(mktemp)"
if [ "$listed" = "1" ]; then
emit_index "$current" "$channel" "$version" --existing-dirs "$existing_dirs" >"$new_index"
else
emit_index "$current" "$channel" "$version" >"$new_index"
fi
aws_s3 s3 cp "$new_index" "s3://${DIFYCTL_R2_BUCKET}/${pointer_prefix}/index.json" \
--content-type application/json --cache-control "public, max-age=60, must-revalidate"
# 5. manifest.json — pointer; written last so it never references missing binaries
manifest="$(mktemp)"
node "${_dir}/release-r2-edge.mjs" manifest --channel "$channel" --version "$version" \
--commit "${DIFYCTL_COMMIT:-unknown}" --build-date "${DIFYCTL_BUILD_DATE:-unknown}" \
--base-url "$base_url" --checksums "${DIST_DIR}/difyctl-v${version}-checksums.txt" >"$manifest"
aws_s3 s3 cp "$manifest" "s3://${DIFYCTL_R2_BUCKET}/${pointer_prefix}/manifest.json" \
--content-type application/json --cache-control "public, max-age=60, must-revalidate"
}
# emit_index <current> <channel> <version> [extra args...] — wrapper so the
# survivor flag can be omitted without tripping `set -u` on empty arrays (bash 3.2).
emit_index() {
local current="$1" channel="$2" version="$3"; shift 3
node "${_dir}/release-r2-edge.mjs" index --current "$current" --channel "$channel" \
--version "$version" --commit "${DIFYCTL_COMMIT:-unknown}" --build-date "${DIFYCTL_BUILD_DATE:-unknown}" "$@"
}
if [ "${RELEASE_PUBLISH_LIB:-0}" != "1" ]; then
[ "$#" -eq 2 ] || { echo "usage: release-r2-publish.sh <channel> <version>" >&2; exit 2; }
publish_main "$1" "$2"
fi
@@ -0,0 +1,91 @@
import { spawnSync } from 'node:child_process'
import { fileURLToPath } from 'node:url'
import { describe, expect, it } from 'vite-plus/test'
const SCRIPT = fileURLToPath(new URL('./release-r2-publish.sh', import.meta.url))
// Stub `aws` + `curl` + `node` as shell functions that just log action verbs to
// $ORDER_LOG, then run the publish `main` and assert the order of operations.
function runPublish(): { code: number; order: string[]; stderr: string } {
const stub = [
'ORDER_LOG="$(mktemp)"',
'aws() {',
' case "$*" in',
' *"list-objects-v2"*) echo list-survivors >>"$ORDER_LOG" ;;',
' *" cp "*"/index.json"*) echo put-index >>"$ORDER_LOG" ;;',
' *" cp "*"/manifest.json"*) echo put-manifest >>"$ORDER_LOG" ;;',
' *" sync "*) echo sync-binaries >>"$ORDER_LOG" ;;',
' *"head-object"*) echo head-verify >>"$ORDER_LOG" ;;',
' *) : ;;',
' esac',
'}',
'curl() { echo "{}"; }',
'node() {',
' case "$*" in',
' *release-naming.mjs*targets*)',
" printf 'bun-linux-x64\\tlinux-x64\\t0\\nbun-linux-arm64\\tlinux-arm64\\t0\\nbun-darwin-x64\\tdarwin-x64\\t0\\nbun-darwin-arm64\\tdarwin-arm64\\t0\\nbun-windows-x64\\twindows-x64\\t1\\n' ;;",
" *release-naming.mjs*' asset '*) printf 'difyctl-vX\\n' ;;",
" *release-r2-edge.mjs*' index '*) echo '{}' ;;",
" *release-r2-edge.mjs*' manifest '*) echo '{}' ;;",
' *) : ;;',
' esac',
'}',
].join('\n')
const program = [
stub,
`. "${SCRIPT}"`,
'publish_main edge 0.1.0-edge.2fd7b82',
'cat "$ORDER_LOG"',
].join('\n')
// bash, NOT sh: the script uses BASH_SOURCE + process substitution.
const r = spawnSync('bash', ['-c', program], {
encoding: 'utf8',
env: {
...process.env,
RELEASE_PUBLISH_LIB: '1',
DIFYCTL_R2_S3_ENDPOINT: 'https://endpoint.example',
DIFYCTL_R2_BUCKET: 'cli-dev',
DIFYCTL_R2_PUBLIC_BASE: 'https://pub.example.r2.dev',
DIST_DIR: '/tmp',
},
})
return {
code: r.status ?? 1,
order: (r.stdout ?? '').trim().split('\n').filter(Boolean),
stderr: r.stderr ?? '',
}
}
describe('release-r2-publish order', () => {
it('uploads binaries, verifies, lists survivors, then index, then manifest', () => {
const { code, order } = runPublish()
expect(code).toBe(0)
expect(order.indexOf('sync-binaries')).toBeLessThan(order.indexOf('head-verify'))
expect(order.indexOf('head-verify')).toBeLessThan(order.indexOf('list-survivors'))
expect(order.indexOf('list-survivors')).toBeLessThan(order.indexOf('put-index'))
expect(order.indexOf('put-index')).toBeLessThan(order.indexOf('put-manifest'))
// pointer is never pruned here — deletion is owned by the R2 lifecycle rule
expect(order).not.toContain('prune')
})
it('exits non-zero when no targets resolve (head-verify safety gate)', () => {
const stub = [
'aws() { :; }',
'curl() { echo "{}"; }',
'node() { case "$*" in *release-naming.mjs*targets*) : ;; *) echo "{}" ;; esac; }',
].join('\n')
const program = [stub, `. "${SCRIPT}"`, 'publish_main edge 0.1.0-edge.2fd7b82'].join('\n')
const r = spawnSync('bash', ['-c', program], {
encoding: 'utf8',
env: {
...process.env,
RELEASE_PUBLISH_LIB: '1',
DIFYCTL_R2_S3_ENDPOINT: 'https://endpoint.example',
DIFYCTL_R2_BUCKET: 'cli-dev',
DIFYCTL_R2_PUBLIC_BASE: 'https://pub.example.r2.dev',
DIST_DIR: '/tmp',
},
})
expect(r.status).not.toBe(0)
})
})
+18
View File
@@ -0,0 +1,18 @@
#!/usr/bin/env bash
# scripts/release-smoke.sh <bin> — run a built binary on this runner and check that
# `install skills` writes exactly the skill tree in skills/difyctl.
set -euo pipefail
_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=lib/common.sh
source "${_dir}/lib/common.sh"
bin="${1:?usage: release-smoke.sh <bin>}"
skill_dir="$(cd "$(cli::root)/.." && pwd)/skills/difyctl"
out="$(mktemp -d)"
trap 'rm -rf "$out"' EXIT
"$bin" version
"$bin" install skills "$out"
diff -r "${out}/difyctl" "$skill_dir"
+42
View File
@@ -0,0 +1,42 @@
#!/usr/bin/env bash
# scripts/release-write-checksums.sh — write sha256 manifest for release binaries.
#
# Required env: CLI_VERSION (e.g. 0.1.0-rc.1). Output:
# cli/dist/bin/difyctl-v<CLI_VERSION>-checksums.txt
set -euo pipefail
_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=lib/common.sh
source "${_dir}/lib/common.sh"
naming() { node "${_dir}/release-naming.mjs" "$@"; }
CLI_VERSION="${CLI_VERSION:-$(node -p "require('$(cli::root)/package.json').version")}"
[[ -n "$CLI_VERSION" && "$CLI_VERSION" != "undefined" ]] || die "CLI_VERSION could not be derived from package.json"
cd "$(cli::root)/dist/bin"
manifest="$(naming checksums "$CLI_VERSION")"
asset_prefix="$(naming tag-prefix)${CLI_VERSION}-"
: > "$manifest"
if command -v sha256sum >/dev/null 2>&1; then
hash_cmd="sha256sum"
elif command -v shasum >/dev/null 2>&1; then
hash_cmd="shasum -a 256"
else
die "no sha256 hasher found (need sha256sum or shasum)"
fi
found=0
for bin in "${asset_prefix}"*; do
[[ -f "$bin" ]] || continue
[[ "$bin" == "$manifest" ]] && continue
$hash_cmd "$bin" >> "$manifest"
found=$((found + 1))
done
[[ "$found" -gt 0 ]] || die "no binaries matching ${asset_prefix}* in dist/bin/"
log::info "wrote ${manifest} (${found} entries)"
+72
View File
@@ -0,0 +1,72 @@
#!/usr/bin/env -S bun
// scripts/run-smoke.ts — five checks against a running Dify server (or mock),
// through `bun bin/dev.js`. DIFY_SERVER, DIFY_TOKEN and DIFY_CONFIG_DIR are
// read from the environment and passed through unchanged.
import { execFileSync, spawnSync } from 'node:child_process'
import { ExitCode } from '../src/errors/codes.js'
type Check = { name: string; run: () => void }
function cli(args: string[]): string {
return execFileSync('bun', ['bin/dev.js', ...args], { encoding: 'utf8' })
}
function cliExitCode(args: string[]): number {
return spawnSync('bun', ['bin/dev.js', ...args], { encoding: 'utf8' }).status ?? 1
}
function expectExit(args: string[], expected: number): void {
const code = cliExitCode(args)
if (code !== expected)
throw new Error(`expected exit ${expected} for "${args.join(' ')}", got ${code}`)
}
const checks: Check[] = [
{
name: 'version prints .client.version',
run: () => {
const body = JSON.parse(cli(['version']))
if (typeof body.client?.version !== 'string') throw new Error('no .client.version')
},
},
{
name: 'help get.console_app carries .input.properties.workspace_id',
run: () => {
const body = JSON.parse(cli(['help', 'get.console_app', '--json']))
if (body.input?.properties?.workspace_id === undefined)
throw new Error('no .input.properties.workspace_id')
},
},
{
name: 'get console_app returns .data',
run: () => {
const body = JSON.parse(cli(['get', 'console_app', '--input', '{"limit":1}']))
if (body.data === undefined) throw new Error('no .data')
},
},
{
name: '--stream on an object-kind op exits 2 (usage)',
run: () =>
expectExit(
['describe', 'console_app', '--input', '{"app_id":"x"}', '--stream'],
ExitCode.Usage,
),
},
{
name: 'a missing required input exits 2 (usage)',
run: () => expectExit(['describe', 'console_app', '--input', '{}'], ExitCode.Usage),
},
]
let failed = 0
for (const c of checks) {
try {
c.run()
console.log(`[x] ${c.name}`)
} catch (err) {
failed++
console.log(`[ ] ${c.name} — ${(err as Error).message}`)
}
}
console.log(`\n${checks.length - failed}/${checks.length} checks passed`)
process.exit(failed > 0 ? 1 : 0)
+12
View File
@@ -0,0 +1,12 @@
#!/bin/sh
# uninstall-local.sh — remove a locally installed difyctl.
# Run via: pnpm uninstall:local
set -eu
PREFIX="${DIFYCTL_PREFIX:-${HOME}/.local}"
SHARE_DIR="${PREFIX}/share/difyctl"
BIN_LINK="${PREFIX}/bin/difyctl"
rm -rf "$SHARE_DIR"
rm -f "$BIN_LINK"
echo "removed ${SHARE_DIR} and ${BIN_LINK}"
@@ -0,0 +1,121 @@
import type { DifyMock } from '@test/fixtures/dify-mock/server'
import type { ServerResponse } from 'node:http'
import type { AddressInfo } from 'node:net'
import { createServer } from 'node:http'
import { startMock } from '@test/fixtures/dify-mock/server'
import { afterEach, expect, it } from 'vite-plus/test'
import { deviceApi } from './device-api'
const mocks: DifyMock[] = []
afterEach(async () => {
for (const m of mocks.splice(0)) await m.stop()
})
// A one-shot raw HTTP server for responses the shared dify-mock has no scenario
// for (an RFC 8628 pending poll, a malformed code response).
async function withServer<T>(
handler: (res: ServerResponse) => void,
fn: (baseUrl: string) => Promise<T>,
): Promise<T> {
const server = createServer((_req, res) => handler(res))
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', () => resolve()))
const { port } = server.address() as AddressInfo
try {
return await fn(`http://127.0.0.1:${port}`)
} finally {
await new Promise<void>((resolve, reject) =>
server.close((err) => (err ? reject(err) : resolve())),
)
}
}
it('maps a 404 on the code endpoint to a server_error naming the missing feature', async () => {
const mock = await startMock({ scenario: 'no-device-flow' })
mocks.push(mock)
const api = deviceApi(mock.url, { insecure: true })
await expect(api.requestCode({ device_label: 'test' })).rejects.toMatchObject({
code: 'server_error',
message: 'this Dify host does not implement the OAuth device flow',
})
})
it('maps a non-2xx code response to a server_error carrying the raw body', async () => {
const mock = await startMock({ scenario: 'server-5xx' })
mocks.push(mock)
const api = deviceApi(mock.url, { insecure: true })
await expect(api.requestCode({ device_label: 'test' })).rejects.toMatchObject({
code: 'server_error',
rawResponse: expect.stringContaining('upstream broken'),
})
})
it('maps an unreachable server to network_connection', async () => {
const mock = await startMock()
const { port } = mock
await mock.stop()
const api = deviceApi(`http://127.0.0.1:${port}`, { insecure: true })
await expect(api.requestCode({ device_label: 'test' })).rejects.toMatchObject({
code: 'network_connection',
})
})
it('maps the RFC 8628 poll error codes to their statuses', async () => {
const mock = await startMock({ scenario: 'denied' })
mocks.push(mock)
const api = deviceApi(mock.url, { insecure: true })
await expect(api.pollOnce({ device_code: 'dc' })).resolves.toEqual({ status: 'denied' })
mock.setScenario('expired')
await expect(api.pollOnce({ device_code: 'dc' })).resolves.toEqual({ status: 'expired' })
mock.setScenario('slow-down')
await expect(api.pollOnce({ device_code: 'dc' })).resolves.toEqual({ status: 'slow_down' })
mock.setScenario('happy')
const approved = await api.pollOnce({ device_code: 'dc' })
expect(approved.status).toBe('approved')
})
it('reports authorization_pending as a pending poll', async () => {
await withServer(
(res) => {
res.writeHead(400, { 'content-type': 'application/json' })
res.end(JSON.stringify({ error: 'authorization_pending' }))
},
async (baseUrl) => {
const api = deviceApi(baseUrl, { insecure: true })
await expect(api.pollOnce({ device_code: 'dc' })).resolves.toEqual({ status: 'pending' })
},
)
})
it('rejects an incomplete code response without leaking a raw parse error', async () => {
await withServer(
(res) => {
res.writeHead(200, { 'content-type': 'application/json' })
res.end(JSON.stringify({ device_code: 'dc' }))
},
async (baseUrl) => {
const api = deviceApi(baseUrl, { insecure: true })
await expect(api.requestCode({ device_label: 'test' })).rejects.toMatchObject({
code: 'server_error',
message: expect.stringContaining('user_code'),
})
},
)
})
it('rejects a non-JSON code response without leaking a raw SyntaxError', async () => {
await withServer(
(res) => {
res.writeHead(200, { 'content-type': 'text/plain' })
res.end('not json')
},
async (baseUrl) => {
const api = deviceApi(baseUrl, { insecure: true })
await expect(api.requestCode({ device_label: 'test' })).rejects.toMatchObject({
code: 'server_error',
})
},
)
})
+206
View File
@@ -0,0 +1,206 @@
import type { Dispatcher } from 'undici'
import { BaseError, HttpClientError } from '@/errors/base'
import { ErrorCode } from '@/errors/codes'
import { buildFetchInit } from '@/net/fetch-init'
import { proxyDispatcher } from '@/net/proxy'
export const DEFAULT_CLIENT_ID = 'difyctl'
export type CodeRequest = {
client_id?: string
device_label: string
}
export type CodeResponse = {
device_code: string
user_code: string
verification_uri: string
expires_in: number
interval: number
}
export type PollRequest = {
client_id?: string
device_code: string
}
export type PollAccount = {
id: string
email: string
name: string
}
export type PollWorkspace = {
id: string
name: string
role: string
}
export type PollSuccess = {
token: string
expires_at?: string
subject_type?: string
subject_email?: string
subject_issuer?: string
account?: PollAccount | null
workspaces?: readonly PollWorkspace[]
default_workspace_id?: string
token_id?: string
}
export type PollResult =
| { status: 'pending' }
| { status: 'slow_down' }
| { status: 'expired' }
| { status: 'denied' }
| { status: 'retry_5xx' }
| { status: 'approved'; success: PollSuccess }
export type DeviceApi = {
readonly requestCode: (req: CodeRequest) => Promise<CodeResponse>
readonly pollOnce: (req: PollRequest) => Promise<PollResult>
}
export type DeviceApiOptions = Readonly<{ insecure: boolean }>
const DEVICE_CODE_PATH = '/openapi/v1/oauth/device/code'
const DEVICE_TOKEN_PATH = '/openapi/v1/oauth/device/token'
const DEVICE_FLOW_UNSUPPORTED_MESSAGE = 'this Dify host does not implement the OAuth device flow'
const HttpStatus = { NotFound: 404, ServerErrorFloor: 500 } as const
// RFC 8628 error codes, mapped to the states awaitAuthorization polls on.
const POLL_ERROR_STATUS: Readonly<Record<string, PollResult['status']>> = {
authorization_pending: 'pending',
slow_down: 'slow_down',
expired_token: 'expired',
access_denied: 'denied',
}
type PollPayload = { error?: string } & Partial<PollSuccess>
const CODE_RESPONSE_REQUIRED_FIELDS = ['device_code', 'user_code', 'verification_uri'] as const
function parseCodeResponse(text: string): CodeResponse {
let payload: Record<string, unknown>
try {
payload = text === '' ? {} : (JSON.parse(text) as Record<string, unknown>)
} catch (cause) {
throw new BaseError({
code: ErrorCode.ServerError,
message: 'device/code response is not valid JSON',
cause,
})
}
const missing = CODE_RESPONSE_REQUIRED_FIELDS.filter(
(field) => typeof payload[field] !== 'string' || payload[field] === '',
)
if (missing.length > 0) {
throw new BaseError({
code: ErrorCode.ServerError,
message: `device/code response missing ${missing.join(', ')}`,
})
}
return payload as unknown as CodeResponse
}
function unsupportedDeviceFlow(method: string, url: URL): HttpClientError {
return new HttpClientError({
code: ErrorCode.ServerError,
message: DEVICE_FLOW_UNSUPPORTED_MESSAGE,
httpStatus: HttpStatus.NotFound,
method,
url: url.toString(),
})
}
async function nonOkError(method: string, url: URL, res: Response): Promise<HttpClientError> {
const rawResponse = await res.text()
return new HttpClientError({
code: ErrorCode.ServerError,
message: `${method} ${url.pathname} failed: HTTP ${res.status}`,
httpStatus: res.status,
method,
url: url.toString(),
rawResponse,
})
}
function parsePollPayload(text: string): PollPayload {
if (text === '') return {}
try {
return JSON.parse(text) as PollPayload
} catch (cause) {
throw new BaseError({
code: ErrorCode.Unknown,
message: `decode poll response: ${(cause as Error).message}`,
cause,
})
}
}
export function deviceApi(server: string, opts: DeviceApiOptions): DeviceApi {
const dispatcher: Dispatcher | undefined = opts.insecure
? proxyDispatcher({ insecure: true })
: proxyDispatcher()
async function post(path: string, body: unknown): Promise<{ url: URL; res: Response }> {
const url = new URL(path, server)
const init = buildFetchInit(
{
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
body: JSON.stringify(body),
},
{ insecure: opts.insecure, dispatcher },
)
try {
return { url, res: await fetch(url, init) }
} catch (cause) {
throw new BaseError({
code: ErrorCode.NetworkConnection,
message: `network error calling POST ${url}`,
cause,
})
}
}
return {
requestCode: async (req) => {
const { url, res } = await post(DEVICE_CODE_PATH, {
client_id: req.client_id ?? DEFAULT_CLIENT_ID,
device_label: req.device_label,
})
if (res.status === HttpStatus.NotFound) throw unsupportedDeviceFlow('POST', url)
if (!res.ok) throw await nonOkError('POST', url, res)
return parseCodeResponse(await res.text())
},
pollOnce: async (req) => {
const { url, res } = await post(DEVICE_TOKEN_PATH, {
client_id: req.client_id ?? DEFAULT_CLIENT_ID,
device_code: req.device_code,
})
if (res.status === HttpStatus.NotFound) throw unsupportedDeviceFlow('POST', url)
if (res.status >= HttpStatus.ServerErrorFloor) return { status: 'retry_5xx' }
const payload = parsePollPayload(await res.text())
if (typeof payload.error === 'string' && payload.error !== '') {
const status = POLL_ERROR_STATUS[payload.error]
if (status === undefined) {
throw new BaseError({
code: ErrorCode.Unknown,
message: `unknown poll error "${payload.error}"`,
})
}
return { status } as PollResult
}
if (typeof payload.token !== 'string' || payload.token === '') {
throw new BaseError({
code: ErrorCode.Unknown,
message: `poll: ${res.status} with no OAuth envelope`,
})
}
return { status: 'approved', success: payload as PollSuccess }
},
}
}
@@ -0,0 +1,228 @@
import type { CodeResponse, PollRequest, PollResult, PollSuccess } from './device-api'
import type { Clock } from './device-flow'
import { startMock } from '@test/fixtures/dify-mock/server'
import { describe, expect, it, vi } from 'vite-plus/test'
import { BaseError } from '@/errors/base'
import { ErrorCode, ExitCode } from '@/errors/codes'
import { isCancelled } from '@/plugins/commands/cancel'
import { deviceApi } from './device-api'
import {
awaitAuthorization,
DEFAULT_INTERVAL_MS,
MAX_INTERVAL_MS,
POLL_RETRY_ATTEMPTS,
POLL_RETRY_CAP_MS,
POLL_RETRY_INITIAL_MS,
pollAuthorization,
realClock,
} from './device-flow'
const successPayload: PollSuccess = {
token: 'dfoa_xyz',
account: { id: 'a', email: 'e', name: 'n' },
workspaces: [{ id: 'w', name: 'W', role: 'owner' }],
default_workspace_id: 'w',
token_id: 't',
}
class FakeClock implements Clock {
sleeps: number[] = []
cancelled = false
cancelAt: number | undefined
async sleepMs(ms: number): Promise<void> {
this.sleeps.push(ms)
if (this.cancelAt !== undefined && this.sleeps.length >= this.cancelAt) this.cancelled = true
}
isCancelled(): boolean {
return this.cancelled
}
}
function fakeApi(scripted: PollResult[]): { pollOnce: (req: PollRequest) => Promise<PollResult> } {
let i = 0
return {
pollOnce: async () => {
const r = scripted[i++]
if (r === undefined) throw new Error('scripted-api: out of responses')
return r
},
}
}
const code: CodeResponse = {
device_code: 'dc',
user_code: 'ABCD-1234',
verification_uri: 'https://dify.example/device',
expires_in: 900,
interval: 1,
}
describe('awaitAuthorization', () => {
it('returns success on first approved poll', async () => {
const api = fakeApi([{ status: 'approved', success: successPayload }])
const clock = new FakeClock()
const result = await awaitAuthorization(api, code, { clock })
expect(result.token).toBe('dfoa_xyz')
expect(clock.sleeps).toHaveLength(0)
})
it('keeps polling on pending then returns approved', async () => {
const api = fakeApi([
{ status: 'pending' },
{ status: 'pending' },
{ status: 'approved', success: successPayload },
])
const clock = new FakeClock()
const result = await awaitAuthorization(api, code, { clock })
expect(result.token).toBe('dfoa_xyz')
expect(clock.sleeps).toEqual([1000, 1000])
})
it('doubles interval on slow_down (capped at max)', async () => {
const api = fakeApi([
{ status: 'slow_down' },
{ status: 'slow_down' },
{ status: 'approved', success: successPayload },
])
const clock = new FakeClock()
const result = await awaitAuthorization(api, code, { clock })
expect(result.token).toBe('dfoa_xyz')
expect(clock.sleeps).toEqual([2000, 4000])
})
it('caps interval at MAX_INTERVAL_MS', async () => {
const api = fakeApi([
{ status: 'slow_down' },
{ status: 'slow_down' },
{ status: 'slow_down' },
{ status: 'slow_down' },
{ status: 'slow_down' },
{ status: 'slow_down' },
{ status: 'slow_down' },
{ status: 'approved', success: successPayload },
])
const clock = new FakeClock()
await awaitAuthorization(api, { ...code, interval: 10 }, { clock })
const last = clock.sleeps[clock.sleeps.length - 1]!
expect(last).toBe(MAX_INTERVAL_MS)
})
it('throws BaseError on expired', async () => {
const api = fakeApi([{ status: 'expired' }])
const clock = new FakeClock()
await expect(awaitAuthorization(api, code, { clock })).rejects.toThrow(/expired/)
})
it('throws BaseError on denied', async () => {
const api = fakeApi([{ status: 'denied' }])
const clock = new FakeClock()
await expect(awaitAuthorization(api, code, { clock })).rejects.toThrow(/denied/)
})
it('uses default interval when CodeResponse.interval is 0', async () => {
const api = fakeApi([{ status: 'pending' }, { status: 'approved', success: successPayload }])
const clock = new FakeClock()
await awaitAuthorization(api, { ...code, interval: 0 }, { clock })
expect(clock.sleeps[0]).toBe(DEFAULT_INTERVAL_MS)
})
it('rejects when clock signals cancelled', async () => {
const api = fakeApi([
{ status: 'pending' },
{ status: 'pending' },
{ status: 'pending' },
{ status: 'pending' },
{ status: 'approved', success: successPayload },
])
const clock = new FakeClock()
clock.cancelAt = 2
// Cancelling is neither an expiry (exit 4) nor a usage mistake (exit 2).
const err = await awaitAuthorization(api, code, { clock }).catch((e: unknown) => e)
expect(err).toMatchObject({ code: 'unknown', message: 'cancelled' })
expect((err as BaseError).exit()).toBe(ExitCode.Generic)
})
it('realClock reports the run-wide cancellation flag, not a constant', async () => {
expect(realClock().isCancelled).toBe(isCancelled)
expect(realClock().isCancelled()).toBe(false)
})
it('exposes constants matching Go reference', () => {
expect(POLL_RETRY_ATTEMPTS).toBe(5)
expect(POLL_RETRY_INITIAL_MS).toBe(1000)
expect(POLL_RETRY_CAP_MS).toBe(16_000)
expect(MAX_INTERVAL_MS).toBe(60_000)
expect(DEFAULT_INTERVAL_MS).toBe(5000)
})
it('preserves dfoe_ token kind through state machine', async () => {
const externalSuccess: PollSuccess = {
token: 'dfoe_xxx',
subject_type: 'external_sso',
subject_email: 'sso@x.com',
subject_issuer: 'https://issuer',
}
const api = fakeApi([{ status: 'approved', success: externalSuccess }])
const clock = new FakeClock()
const result = await awaitAuthorization(api, code, { clock })
expect(result.token).toBe('dfoe_xxx')
expect(result.subject_type).toBe('external_sso')
})
it('propagates BaseError thrown by api.pollOnce', async () => {
const api = {
pollOnce: vi
.fn()
.mockRejectedValue(new BaseError({ code: ErrorCode.ServerError, message: 'old server' })),
}
const clock = new FakeClock()
await expect(awaitAuthorization(api, code, { clock })).rejects.toThrow(/old server/)
})
})
it('does not retry device polling after cancellation during backoff', async () => {
const mock = await startMock({ scenario: 'server-5xx' })
const clock = new FakeClock()
clock.sleepMs = async (ms) => {
clock.sleeps.push(ms)
clock.cancelled = true
mock.setScenario('happy')
}
try {
const api = deviceApi(mock.url, { insecure: true })
await expect(awaitAuthorization(api, code, { clock })).rejects.toMatchObject({
code: ErrorCode.Unknown,
message: 'cancelled',
})
expect(mock.requestCount).toBe(1)
expect(clock.sleeps).toEqual([POLL_RETRY_INITIAL_MS])
} finally {
await mock.stop()
}
})
it('does not poll a resumed authorization when already cancelled', async () => {
const pollOnce = vi.fn().mockResolvedValue({ status: 'approved', success: successPayload })
const clock = new FakeClock()
clock.cancelled = true
await expect(pollAuthorization({ pollOnce }, code.device_code, { clock })).rejects.toMatchObject({
code: ErrorCode.Unknown,
message: 'cancelled',
})
expect(pollOnce).not.toHaveBeenCalled()
})
it('does not accept approval if cancellation happened while polling', async () => {
const clock = new FakeClock()
const pollOnce = async (): Promise<PollResult> => {
clock.cancelled = true
return { status: 'approved', success: successPayload }
}
await expect(awaitAuthorization({ pollOnce }, code, { clock })).rejects.toMatchObject({
code: ErrorCode.Unknown,
message: 'cancelled',
})
expect(clock.sleeps).toEqual([])
})
+123
View File
@@ -0,0 +1,123 @@
import type { CodeResponse, PollRequest, PollResult, PollSuccess } from './device-api'
import { BaseError } from '@/errors/base'
import { ErrorCode } from '@/errors/codes'
import { isCancelled } from '@/plugins/commands/cancel'
import { DEFAULT_CLIENT_ID } from './device-api'
export const DEFAULT_INTERVAL_MS = 5_000
export const MAX_INTERVAL_MS = 60_000
export const POLL_RETRY_ATTEMPTS = 5
export const POLL_RETRY_INITIAL_MS = 1_000
export const POLL_RETRY_CAP_MS = 16_000
const CANCELLED_MESSAGE = 'cancelled'
export type Clock = {
sleepMs: (ms: number) => Promise<void>
isCancelled: () => boolean
}
export type DeviceFlowApiSubset = {
pollOnce: (req: PollRequest) => Promise<PollResult>
}
export type AwaitOptions = {
clock: Clock
clientId?: string
}
export async function awaitAuthorization(
api: DeviceFlowApiSubset,
code: CodeResponse,
opts: AwaitOptions,
): Promise<PollSuccess> {
if (code.device_code === '') throw expired()
const baseInterval = code.interval > 0 ? code.interval * 1000 : DEFAULT_INTERVAL_MS
let interval = baseInterval
const req = pollRequest(code.device_code, opts)
while (true) {
if (opts.clock.isCancelled()) throw cancelledError()
const result = await pollWithRetry(api, req, opts.clock)
const success = settle(result)
if (success !== undefined) return success
if (result.status === 'slow_down') interval = Math.min(interval * 2, MAX_INTERVAL_MS)
await opts.clock.sleepMs(interval)
if (opts.clock.isCancelled()) throw cancelledError()
}
}
export async function pollAuthorization(
api: DeviceFlowApiSubset,
deviceCode: string,
opts: AwaitOptions,
): Promise<PollSuccess | undefined> {
return settle(await pollWithRetry(api, pollRequest(deviceCode, opts), opts.clock))
}
function pollRequest(deviceCode: string, opts: AwaitOptions): PollRequest {
return { device_code: deviceCode, client_id: opts.clientId ?? DEFAULT_CLIENT_ID }
}
function settle(result: PollResult): PollSuccess | undefined {
switch (result.status) {
case 'approved':
return result.success
case 'pending':
case 'slow_down':
return undefined
case 'expired':
throw expired()
case 'denied':
throw new BaseError({
code: ErrorCode.AccessDenied,
message: 'authorization denied',
})
case 'retry_5xx':
throw new BaseError({
code: ErrorCode.ServerError,
message: 'device-flow poll unavailable after retries',
})
}
}
async function pollWithRetry(
api: DeviceFlowApiSubset,
req: PollRequest,
clock: Clock,
): Promise<PollResult> {
let backoff = POLL_RETRY_INITIAL_MS
for (let attempt = 1; attempt <= POLL_RETRY_ATTEMPTS; attempt++) {
if (clock.isCancelled()) throw cancelledError()
const result = await api.pollOnce(req)
if (clock.isCancelled()) throw cancelledError()
if (result.status !== 'retry_5xx') return result
if (attempt === POLL_RETRY_ATTEMPTS) break
await clock.sleepMs(backoff)
backoff = Math.min(backoff * 2, POLL_RETRY_CAP_MS)
}
return { status: 'retry_5xx' }
}
function expired(): BaseError {
return new BaseError({
code: ErrorCode.AuthExpired,
message: 'code expired before authorization',
})
}
// Ctrl-C during the wait is neither an expiry nor a usage mistake: the code is still
// good, the operator just stopped waiting for it.
function cancelledError(): BaseError {
return new BaseError({ code: ErrorCode.Unknown, message: CANCELLED_MESSAGE })
}
export function realClock(): Clock {
return {
async sleepMs(ms) {
await new Promise<void>((r) => setTimeout(r, ms))
},
isCancelled,
}
}
+45
View File
@@ -0,0 +1,45 @@
import type { CommandContext } from '@/plugins/base'
import type { Login } from '@/plugins/session'
import { BaseError } from '@/errors/base'
import { ErrorCode } from '@/errors/codes'
import { errorMessage } from '@/errors/message'
import { catalog } from '@/plugins/catalog'
import { http } from '@/plugins/http'
import { io } from '@/plugins/io'
import { session } from '@/plugins/session'
import { token } from '@/plugins/token'
const SESSIONS_SELF_PATH = '/openapi/v1/account/sessions/self'
const REVOKE_FAILED_PREFIX = 'server revoke failed: '
/** Throws when the current login comes from DIFY_SERVER/DIFY_TOKEN, which neither
* login nor logout may touch — each passes its own explanation. */
export function assertNotEnvLogin(fromEnv: boolean, message: string): void {
if (fromEnv) throw new BaseError({ code: ErrorCode.UsageInvalidFlag, message })
}
// Shared by `login` (logging out a previous session before starting a new one)
// and `logout` itself: best-effort server-side revoke, then unconditional local
// cleanup of the token, the cached catalog and the session pin.
//
// catalog.clear() must run before session.clear(): the catalog plugin resolves
// its cache-file path from session.current() the first time it is built, so
// clearing the session first leaves it unable to find its own file.
export async function revokeAndClearSession(ctx: CommandContext, login: Login): Promise<void> {
const streams = await ctx.get(io)
const httpService = await ctx.get(http)
try {
await httpService.request(() => ({ method: 'DELETE', path: SESSIONS_SELF_PATH }))
} catch (err) {
streams.notice(`${REVOKE_FAILED_PREFIX}${errorMessage(err)}`)
}
const tokenService = await ctx.get(token)
await tokenService.remove(login)
const catalogService = await ctx.get(catalog)
await catalogService.clear()
const sessionService = await ctx.get(session)
await sessionService.clear()
}
@@ -0,0 +1,41 @@
import type { CommandContext } from '@/plugins/base'
import { join } from 'node:path'
import { z } from 'zod'
import { env } from '@/plugins/env'
import { io } from '@/plugins/io'
import { localFile, REMOVE } from '@/store/local-file'
export const PENDING_FILE_NAME = 'login-pending.yml'
const PENDING_SCHEMA = z.object({
server: z.string(),
insecure: z.boolean(),
no_keyring: z.boolean(),
device_code: z.string(),
})
export type Pending = z.infer<typeof PENDING_SCHEMA>
export type PendingLoginStore = Readonly<{
read: () => Promise<Pending | null>
save: (pending: Pending) => Promise<void>
clear: () => Promise<void>
/** Clear only while the file still holds `deviceCode`: a newer login's code survives. */
clearIf: (deviceCode: string) => Promise<void>
}>
/** The device code a `login --no-wait` saved for `login --resume` to finish. */
export async function pendingLoginStore(ctx: CommandContext): Promise<PendingLoginStore> {
const { configDir } = await ctx.get(env)
const file = localFile(
join(configDir, PENDING_FILE_NAME),
PENDING_SCHEMA,
(await ctx.get(io)).notice,
)
return {
read: file.read,
save: (pending) => file.update(() => pending),
clear: () => file.update(() => REMOVE),
clearIf: (deviceCode) =>
file.update((pending) => (pending?.device_code === deviceCode ? REMOVE : undefined)),
}
}
+7
View File
@@ -0,0 +1,7 @@
import { BaseError } from '@/errors/base'
import { ErrorCode } from '@/errors/codes'
/** Every rejection of caller-supplied operation input, from load through request building. */
export function inputInvalid(message: string, cause?: unknown): BaseError {
return new BaseError({ code: ErrorCode.InputInvalid, message, cause })
}
+214
View File
@@ -0,0 +1,214 @@
import type { TestWorld } from '@test/fixtures/kernel'
import { writeFileSync } from 'node:fs'
import { join } from 'node:path'
import { testContext } from '@test/fixtures/kernel'
import { afterEach, expect, it } from 'vite-plus/test'
import { commands } from '@/plugins/commands'
const worlds: TestWorld[] = []
async function world(argv: string[]) {
const w = await testContext({ login: true, argv })
worlds.push(w)
return w
}
afterEach(async () => {
for (const w of worlds.splice(0)) await w.stop()
})
it('fills the pin, validates, sends the fingerprint and prints a list with the server hint', async () => {
const w = await world(['get', 'console_app', '--input', '{"limit":1}'])
expect(await (await w.ctx.get(commands)).run()).toBe(0)
expect(w.mock.lastRequest?.path).toBe('/openapi/v1/apps?limit=1&workspace_id=ws-1')
expect(w.mock.lastRequest?.headers['x-dify-catalog']).toHaveLength(64)
expect(JSON.parse(w.io.outBuf()).hints[0]).toMatchObject({
op: 'get.console_app',
input: { workspace_id: 'ws-1', limit: 1, page: 2 },
})
})
it('rejects invalid input with details and the schema, exit 2, before any op request', async () => {
const w = await world(['describe', 'console_app', '--input', '{}'])
await expect((await w.ctx.get(commands)).run()).rejects.toMatchObject({
code: 'input_invalid',
details: [{ type: 'required', loc: ['app_id'] }],
schema: expect.objectContaining({ type: 'object' }),
})
expect(w.mock.requestCount).toBe(1) // only the first-run catalog fetch
})
it('refuses --stream on a non-sse op, exit 2', async () => {
const w = await world(['describe', 'console_app', '--input', '{"app_id":"app-1"}', '--stream'])
await expect((await w.ctx.get(commands)).run()).rejects.toMatchObject({
code: 'usage_invalid_flag',
message: expect.stringContaining('--stream'),
})
})
it('refuses --only without --stream, exit 2, before any op request', async () => {
const w = await world([
'run',
'console_app',
'workflow',
'--input',
'{"app_id":"app-2","inputs":{}}',
'--only',
'workflow_finished',
])
await expect((await w.ctx.get(commands)).run()).rejects.toMatchObject({
code: 'usage_invalid_flag',
message: '--only requires --stream',
})
expect(w.mock.requestCount).toBe(1) // only the first-run catalog fetch
})
it('warns once on stderr for a deprecated op and still runs it', async () => {
const w = await world([
'legacy_run',
'console_app',
'--input',
'{"app_id":"app-1","inputs":{},"query":"hi"}',
])
expect(await (await w.ctx.get(commands)).run()).toBe(0)
expect(w.io.errBuf().trim()).toBe('deprecated: legacy_run.console_app')
expect(JSON.parse(w.io.outBuf())).toMatchObject({
status: 'ended',
text: { answer: 'echo: hi' },
})
})
it('folds a per-mode run and copies the reply hint', async () => {
const w = await world([
'run',
'console_app',
'chat',
'--input',
'{"app_id":"app-1","inputs":{},"query":"hi"}',
])
expect(await (await w.ctx.get(commands)).run()).toBe(0)
expect(JSON.parse(w.io.outBuf())).toMatchObject({
status: 'ended',
text: { answer: 'echo: hi' },
conversation_id: 'conv-1',
hints: [{ op: 'run.console_app.chat', input: { conversation_id: 'conv-1', query: null } }],
})
})
it('streams with --stream --only', async () => {
const w = await world([
'run',
'console_app',
'workflow',
'--input',
'{"app_id":"app-2","inputs":{}}',
'--stream',
'--only',
'workflow_finished',
])
await (await w.ctx.get(commands)).run()
const lines = w.io
.outBuf()
.trim()
.split('\n')
.map((l) => JSON.parse(l))
expect(lines).toHaveLength(1)
expect(lines[0].event).toBe('workflow_finished')
})
it('sends multipart when files are given', async () => {
const seed = await testContext({ login: true })
worlds.push(seed)
const tmp = join(seed.dir, 'r.pdf')
writeFileSync(tmp, 'pdf')
const w = await testContext({
login: true,
argv: [
'run',
'console_app',
'workflow',
'--input',
JSON.stringify({ app_id: 'app-2', inputs: {}, files: { doc: tmp } }),
],
reuseDirOf: seed,
})
worlds.push(w)
await (await w.ctx.get(commands)).run()
expect(w.mock.lastRequest?.contentType).toMatch(/^multipart\/form-data/)
expect(w.mock.lastRunParts?.['files[doc]']).toHaveLength(1)
})
it('a paused run is exit 0 with status suspended and the server hints', async () => {
const w = await world([
'run',
'console_app',
'workflow',
'--input',
'{"app_id":"app-2","inputs":{}}',
])
w.mock.setScenario('hitl-pause')
expect(await (await w.ctx.get(commands)).run()).toBe(0)
expect(JSON.parse(w.io.outBuf())).toMatchObject({
status: 'suspended',
run_id: 'wf-run-hitl-1',
hints: [{ op: 'submit.run.form', input: { form_token: 'ft-hitl-1', action: 'submit' } }],
})
})
it('a form submit prints the hint to follow the run', async () => {
const w = await world([
'submit',
'run',
'form',
'--input',
'{"app_id":"app-2","form_token":"ft-hitl-1","action":"submit","inputs":{"name":"Bob"}}',
])
expect(await (await w.ctx.get(commands)).run()).toBe(0)
expect(JSON.parse(w.io.outBuf()).hints).toEqual([
expect.objectContaining({
op: 'get.run.event',
input: { app_id: 'app-2', run_id: 'wf-run-hitl-1', continue_on_pause: false },
}),
])
})
it('a stale catalog is refreshed once and the op is retried', async () => {
const w = await world(['help'])
await (await w.ctx.get(commands)).run()
w.mock.setScenario('catalog-changed')
const w2 = await testContext({
login: true,
argv: ['ping', 'workspace', '--input', '{"workspace_id":"ws-1"}'],
reuseDirOf: w,
})
worlds.push(w2)
expect(await (await w2.ctx.get(commands)).run()).toBe(0)
})
it('a stream that dies mid-run folds as incomplete, exit 0, with one stderr notice', async () => {
const w = await world([
'run',
'console_app',
'chat',
'--input',
'{"app_id":"app-1","inputs":{},"query":"hi"}',
])
w.mock.setScenario('broken-stream')
expect(await (await w.ctx.get(commands)).run()).toBe(0)
expect(JSON.parse(w.io.outBuf())).toMatchObject({
status: 'incomplete',
text: { answer: 'partial' },
})
expect(w.io.errBuf().trim().split('\n')).toHaveLength(1)
expect(w.io.errBuf()).toMatch(/^stream ended early: /)
})
it('registers the stream abort as a deferred cleanup', async () => {
const w = await world([
'run',
'console_app',
'workflow',
'--input',
'{"app_id":"app-2","inputs":{}}',
])
await (await w.ctx.get(commands)).run()
expect(w.ctx.deferred).toHaveLength(1)
})
+84
View File
@@ -0,0 +1,84 @@
import type { CallFlags } from '@/call/flags'
import type { CommandContext } from '@/plugins/base'
import type { CatalogOp } from '@/plugins/catalog'
import { readFile } from 'node:fs/promises'
import { LOCAL_FILES } from '@/call/files'
import { unsupportedFlags } from '@/call/flags'
import { applyPins, loadInput, resolveFileRefs } from '@/call/input'
import { rendererFor } from '@/call/render/index'
import { buildRequest } from '@/call/request'
import { BaseError } from '@/errors/base'
import { ErrorCode } from '@/errors/codes'
import { runSignal } from '@/plugins/commands/cancel'
import { assertValidInput, Outcome } from '@/plugins/commands/command'
import { http } from '@/plugins/http'
import { io } from '@/plugins/io'
import { session } from '@/plugins/session'
import { KIND } from '@/protocol/kinds'
import { commandWords } from '@/protocol/op-id'
import { PIN } from '@/protocol/pins'
import { flagToken } from '@/util/flag-name'
/** One catalog operation, its call flags, and the fields typed as flags of their own. */
export type CallRequest = Readonly<{
id: string
op: CatalogOp
flags: CallFlags
fields: Record<string, unknown>
}>
const FILE_ENCODING = 'utf8'
const DEPRECATED_NOTICE = 'deprecated'
const ONLY_NEEDS_STREAM = '--only requires --stream'
function assertSupportedFlags(kind: string, flags: CallFlags): void {
const [refused] = unsupportedFlags(kind, flags)
if (refused !== undefined) {
throw new BaseError({
code: ErrorCode.UsageInvalidFlag,
message: `${flagToken(refused)} is not supported by ${kind} operations`,
})
}
// --only filters the events --stream emits; on its own it filters nothing.
if (flags.only !== undefined && flags.stream !== true)
throw new BaseError({ code: ErrorCode.UsageInvalidFlag, message: ONLY_NEEDS_STREAM })
}
async function readAll(stream: NodeJS.ReadableStream): Promise<string> {
stream.setEncoding(FILE_ENCODING)
let text = ''
for await (const chunk of stream) text += chunk
return text
}
export async function executeCall(req: CallRequest, ctx: CommandContext): Promise<Outcome> {
assertSupportedFlags(req.op.kind, req.flags)
const out = await ctx.get(io)
const source = {
stdin: () => readAll(out.streams.in),
readFile: (path: string) => readFile(path, FILE_ENCODING),
}
const whole = await loadInput({ ...source, raw: req.flags.input })
const fields = await resolveFileRefs(req.fields, req.op.input, source)
const workspaceId = await (await ctx.get(session)).workspaceId()
const body = applyPins({ ...whole, ...fields }, req.op.input, { [PIN.Workspace]: workspaceId })
assertValidInput({ command: commandWords(req.id), schema: req.op.input, input: body })
if (req.op.deprecated) out.notice(`${DEPRECATED_NOTICE}: ${req.id}`)
// SIGINT cancels the whole invocation; this controller ends only this call's stream.
const call = new AbortController()
if (req.op.kind === KIND.Sse) ctx.defer(() => call.abort())
const signal = AbortSignal.any([runSignal(), call.signal])
const res = await (
await ctx.get(http)
).request(async (cat) => ({
...(await buildRequest(cat.opOrThrow(req.id), body, LOCAL_FILES)),
signal,
}))
const code = await rendererFor(req.op.kind, out)(res, out, req.flags, req.id)
return new Outcome(code)
}
+91
View File
@@ -0,0 +1,91 @@
import { chmod, mkdir, mkdtemp, rm, symlink, writeFile } from 'node:fs/promises'
import { platform, tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, expect, it } from 'vite-plus/test'
import { isLocalFolder, listLocalFolder } from './files'
const LOCKED = 'locked'
const MIB = 1024 * 1024
let root: string
beforeEach(async () => {
root = await mkdtemp(join(tmpdir(), 'difyctl-files-'))
})
afterEach(async () => {
await chmod(join(root, LOCKED), 0o700).catch(() => undefined)
await rm(root, { recursive: true, force: true })
})
it('lists files recursively, sorted, with / keys', async () => {
await writeFile(join(root, 'b.txt'), 'b')
await mkdir(join(root, 'a'))
await writeFile(join(root, 'a', 'x.md'), 'x')
await writeFile(join(root, 'a', '.env'), 'e')
expect(await listLocalFolder(root)).toEqual(['a/.env', 'a/x.md', 'b.txt'])
})
it('skips OS junk', async () => {
for (const name of ['.DS_Store', 'Thumbs.db', 'desktop.ini', 'keep.txt']) {
await writeFile(join(root, name), '')
}
await mkdir(join(root, '__MACOSX', 'a'), { recursive: true })
await writeFile(join(root, '__MACOSX', 'a', '._x'), '')
expect(await listLocalFolder(root)).toEqual(['keep.txt'])
})
it('keeps a regular file that shares a junk folder name', async () => {
await writeFile(join(root, '__MACOSX'), 'm')
expect(await listLocalFolder(root)).toEqual(['__MACOSX'])
})
it('returns [] when only junk is left', async () => {
await writeFile(join(root, '.DS_Store'), '')
expect(await listLocalFolder(root)).toEqual([])
})
it('tells a folder from a file and a missing path', async () => {
const file = join(root, 'f.txt')
await writeFile(file, 'f')
expect(await isLocalFolder(root)).toBe(true)
expect(await isLocalFolder(file)).toBe(false)
expect(await isLocalFolder(join(root, 'missing'))).toBe(false)
})
it('lists a folder of any size without a cap', async () => {
for (const name of ['a.txt', 'b.txt', 'c.txt']) {
await writeFile(join(root, name), name)
}
await writeFile(join(root, 'd.bin'), new Uint8Array(2 * MIB))
expect(await listLocalFolder(root)).toEqual(['a.txt', 'b.txt', 'c.txt', 'd.bin'])
})
it.skipIf(platform() === 'win32')('rejects a symlink', async () => {
await symlink('..', join(root, 'loop'))
await expect(listLocalFolder(root)).rejects.toMatchObject({
code: 'input_invalid',
message: expect.stringContaining('loop'),
})
})
it.skipIf(platform() === 'win32')('names a nested symlink by its full path', async () => {
await mkdir(join(root, 'sub'))
await symlink('..', join(root, 'sub', 'loop'))
await expect(listLocalFolder(`${root}/`)).rejects.toMatchObject({
code: 'input_invalid',
message: expect.stringContaining(`"${join(root, 'sub', 'loop')}" is a symlink`),
})
})
it.skipIf(platform() === 'win32' || process.getuid?.() === 0)(
'names the unreadable subfolder',
async () => {
await mkdir(join(root, LOCKED))
await chmod(join(root, LOCKED), 0o000)
await expect(listLocalFolder(root)).rejects.toMatchObject({
code: 'input_invalid',
message: `cannot read folder "${join(root, LOCKED)}"`,
})
},
)
+56
View File
@@ -0,0 +1,56 @@
import type { FileDeps, FileReader, FolderCheck, FolderLister } from './request'
import { readFile, stat } from 'node:fs/promises'
import { basename, join } from 'node:path'
import { inputInvalid } from '@/call/errors'
import { BaseError } from '@/errors/base'
import { ENTRY_KIND, KEY_SEPARATOR, walkTree } from '@/sys/tree'
const JUNK_FILES: ReadonlySet<string> = new Set(['.DS_Store', 'Thumbs.db', 'desktop.ini'])
const JUNK_DIRS: ReadonlySet<string> = new Set(['__MACOSX'])
export const readLocalFile: FileReader = async (path) => ({
bytes: await readFile(path),
name: basename(path),
})
export const isLocalFolder: FolderCheck = async (path) =>
(await stat(path).catch(() => undefined))?.isDirectory() === true
function isJunk(path: string): boolean {
const segments = path.split(KEY_SEPARATOR)
const name = segments.pop()
return (
(name !== undefined && JUNK_FILES.has(name)) ||
segments.some((segment) => JUNK_DIRS.has(segment))
)
}
function failedPath(cause: unknown): string | undefined {
const path = (cause as NodeJS.ErrnoException | undefined)?.path
return typeof path === 'string' ? path : undefined
}
export const listLocalFolder: FolderLister = async (path) => {
const files: string[] = []
try {
for await (const entry of walkTree(path)) {
if (entry.kind === ENTRY_KIND.Symlink) {
throw inputInvalid(
`"${join(path, entry.path)}" is a symlink; folders sent as input cannot contain symlinks`,
)
}
if (entry.kind !== ENTRY_KIND.File || isJunk(entry.path)) continue
files.push(entry.path)
}
} catch (cause) {
if (cause instanceof BaseError) throw cause
throw inputInvalid(`cannot read folder "${failedPath(cause) ?? path}"`, cause)
}
return files.sort()
}
export const LOCAL_FILES: FileDeps = {
readFile: readLocalFile,
isFolder: isLocalFolder,
listFolder: listLocalFolder,
}
+10
View File
@@ -0,0 +1,10 @@
import { expect, it } from 'vite-plus/test'
import { unsupportedFlags } from './flags'
it('refuses the flags a kind does not accept and treats an unknown kind as an object', () => {
const all = { input: '{}', stream: true, only: ['a'], output: 'f' }
expect(unsupportedFlags('sse', all)).toEqual(['output'])
expect(unsupportedFlags('file', all)).toEqual(['stream', 'only'])
expect(unsupportedFlags('hologram', { stream: true })).toEqual(['stream'])
expect(unsupportedFlags('object', { input: '{}' })).toEqual([])
})
+74
View File
@@ -0,0 +1,74 @@
import type { JsonSchema } from '@/plugins/catalog'
import type { Kind } from '@/protocol/kinds'
import { z } from 'zod'
import { inputSchema } from '@/plugins/argv/parse'
import { isKind, KIND, KINDS } from '@/protocol/kinds'
export const CALL_FLAG = {
Input: 'input',
Stream: 'stream',
Only: 'only',
Output: 'output',
} as const
export type CallFlag = (typeof CALL_FLAG)[keyof typeof CALL_FLAG]
type FlagSpec<S extends z.ZodType> = Readonly<{ schema: S; kinds: readonly Kind[] }>
function flag<S extends z.ZodType>(schema: S, kinds: readonly Kind[]): FlagSpec<S> {
return { schema, kinds }
}
export const CALL_FLAGS = {
[CALL_FLAG.Input]: flag(
z.string().optional().describe('Operation input as JSON, @file or @- for stdin'),
KINDS,
),
[CALL_FLAG.Stream]: flag(z.boolean().optional().describe('Print each event as it arrives'), [
KIND.Sse,
]),
[CALL_FLAG.Only]: flag(
z.array(z.string()).optional().describe('Keep only these streamed events'),
[KIND.Sse],
),
[CALL_FLAG.Output]: flag(z.string().optional().describe('Write the downloaded file here'), [
KIND.File,
]),
} as const
type SchemasOf<T extends Record<string, FlagSpec<z.ZodType>>> = { [K in keyof T]: T[K]['schema'] }
function schemasOf<T extends Record<string, FlagSpec<z.ZodType>>>(table: T): SchemasOf<T> {
return Object.fromEntries(
Object.entries(table).map(([name, spec]) => [name, spec.schema]),
) as SchemasOf<T>
}
export const CALL_FLAG_SCHEMA = z.object(schemasOf(CALL_FLAGS))
export type CallFlags = z.infer<typeof CALL_FLAG_SCHEMA>
const CALL_FLAG_NAMES = Object.keys(CALL_FLAGS) as readonly CallFlag[]
// An unknown kind is rendered — and so flagged — as an object.
function renderedKind(kind: string): Kind {
return isKind(kind) ? kind : KIND.Object
}
export function unsupportedFlags(kind: string, flags: CallFlags): CallFlag[] {
const renderedAs = renderedKind(kind)
return CALL_FLAG_NAMES.filter(
(name) => flags[name] !== undefined && !CALL_FLAGS[name].kinds.includes(renderedAs),
)
}
/** The call flags an operation of this kind accepts, as a JSON Schema. */
export function callOptionsSchema(kind: string): JsonSchema {
const renderedAs = renderedKind(kind)
const shape = Object.fromEntries(
Object.entries(CALL_FLAGS)
.filter(([, spec]) => spec.kinds.includes(renderedAs))
.map(([name, spec]) => [name, spec.schema]),
)
return inputSchema(z.object(shape))
}
+108
View File
@@ -0,0 +1,108 @@
import { expect, it } from 'vite-plus/test'
import { exitCodeFor, finishFold, foldEvent, newFoldResult } from './fold'
function run(events: [string, Record<string, unknown>][]) {
const r = newFoldResult()
for (const [n, e] of events) foldEvent(r, n, e)
return { result: finishFold(r), code: exitCodeFor(r) }
}
it('folds a chat run and copies the reply hint from message_end', () => {
const hint = {
summary: 'Reply in this conversation',
op: 'run.console_app.chat',
input: { app_id: 'a', conversation_id: 'c1', query: null, inputs: {} },
}
const { result, code } = run([
['message', { answer: 'a' }],
['message', { answer: 'b' }],
['message_end', { message_id: 'm1', conversation_id: 'c1', hints: [hint] }],
])
expect(result).toEqual({
status: 'ended',
text: { answer: 'ab' },
message_id: 'm1',
conversation_id: 'c1',
hints: [hint],
})
expect(code).toBe(0)
})
it('folds a failed workflow without an error event', () => {
const { result, code } = run([
[
'workflow_finished',
{ data: { status: 'failed', outputs: {}, total_tokens: 0, error: 'inputs.q is required' } },
],
])
expect(result.status).toBe('failed')
expect(result.error).toEqual({ message: 'inputs.q is required' })
expect(code).toBe(1)
})
it('keeps text_chunk previews only when incomplete', () => {
const incomplete = run([
['text_chunk', { data: { text: 'so far', from_variable_selector: ['llm_1', 'text'] } }],
])
expect(incomplete.result).toEqual({
status: 'incomplete',
text: { answer: '', by_source: { 'llm_1.text': 'so far' } },
hints: [],
})
const ended = run([
['text_chunk', { data: { text: 'x', from_variable_selector: ['n', 't'] } }],
['workflow_finished', { data: { status: 'succeeded', outputs: { r: 1 } } }],
])
expect(ended.result.text).toEqual({ answer: '' })
expect(ended.result.outputs).toEqual({ r: 1 })
})
it('a late error still wins and unknown events are ignored', () => {
expect(
run([
['message_end', {}],
['error', { message: 'late', code: 'x' }],
]).result.status,
).toBe('failed')
expect(run([['node_started', { id: 'n1' }]]).result.status).toBe('incomplete')
})
it('copies server hints from a pause and suspends; a pause without hints is still suspended', () => {
const hint = {
summary: 'Submit',
op: 'submit.run.form',
input: { app_id: 'a', form_token: 'ft', action: 'submit', inputs: { name: null } },
form: [{ output_variable_name: 'name' }],
}
const paused = run([
['message', { answer: 'x' }],
[
'human_input_required',
{ data: { form_token: 'ft', actions: [{ id: 'submit' }] }, hints: [hint] },
],
])
expect(paused.result).toEqual({ status: 'suspended', text: { answer: 'x' }, hints: [hint] })
expect(paused.code).toBe(0)
const bare = run([
[
'human_input_required',
{ data: { form_token: 'ft', actions: [], approval_channels: ['email'] } },
],
])
expect(bare.result).toEqual({ status: 'suspended', text: { answer: '' }, hints: [] })
})
it('keeps the run id from any event, even one it has no handler for', () => {
const { result, code } = run([
['workflow_started', { workflow_run_id: 'run-1', data: { id: 'run-1' } }],
['human_input_required', { workflow_run_id: 'run-1', hints: [] }],
['workflow_paused', { workflow_run_id: 'run-1' }],
])
expect(result).toMatchObject({ status: 'suspended', run_id: 'run-1' })
expect(code).toBe(0)
})
it('ignores a run id that is not a string', () => {
const { result } = run([['some_future_event', { workflow_run_id: 42 }]])
expect(result).not.toHaveProperty('run_id')
})
+22
View File
@@ -0,0 +1,22 @@
import type { ExitCodeValue } from '@/errors/codes'
import type { FoldResult } from '@/protocol/fold'
import { ExitCode } from '@/errors/codes'
import { FOLD_STATUS, FOLD_TABLE, foldAnyEvent } from '@/protocol/fold'
export function newFoldResult(): FoldResult {
return { status: FOLD_STATUS.Incomplete, text: { answer: '' }, hints: [] }
}
export function foldEvent(result: FoldResult, name: string, event: Record<string, unknown>): void {
foldAnyEvent(result, event)
FOLD_TABLE[name]?.(result, event)
}
export function finishFold(result: FoldResult): FoldResult {
if (result.status !== FOLD_STATUS.Incomplete) delete result.text.by_source
return result
}
export function exitCodeFor(result: FoldResult): ExitCodeValue {
return result.status === FOLD_STATUS.Failed ? ExitCode.Generic : ExitCode.Success
}
+117
View File
@@ -0,0 +1,117 @@
import { expect, it } from 'vite-plus/test'
import { applyPins, loadInput, resolveFileRefs } from './input'
const src = (raw: string | undefined, stdin = '', files: Record<string, string> = {}) => ({
raw,
stdin: async () => stdin,
readFile: async (p: string) => {
const f = files[p]
if (f === undefined) throw new Error('ENOENT')
return f
},
})
it('parses inline json, @file and @- and defaults to {}', async () => {
expect(await loadInput(src('{"a":1}'))).toEqual({ a: 1 })
expect(await loadInput(src('@in.json', '', { 'in.json': '{"b":2}' }))).toEqual({ b: 2 })
expect(await loadInput(src('@-', '{"c":3}'))).toEqual({ c: 3 })
expect(await loadInput(src(undefined))).toEqual({})
})
it('rejects non-object json and unreadable files with input_invalid', async () => {
await expect(loadInput(src('[1]'))).rejects.toMatchObject({ code: 'input_invalid' })
await expect(loadInput(src('nope'))).rejects.toMatchObject({ code: 'input_invalid' })
await expect(loadInput(src('@missing.json'))).rejects.toMatchObject({
code: 'input_invalid',
message: expect.stringContaining('missing.json'),
})
})
const REF_SCHEMA = {
type: 'object',
properties: {
inputs: { type: 'object', properties: {} },
files: { type: 'array', items: { type: 'object', properties: {} } },
query: { type: 'string' },
},
}
const refs = (stdin: string, files: Record<string, string> = {}) => ({
stdin: async () => stdin,
readFile: async (p: string) => {
const f = files[p]
if (f === undefined) throw new Error('ENOENT')
return f
},
})
it('ignores a leading BOM in JSON input without changing string values', async () => {
expect(await loadInput(src('\uFEFF{"a":1}'))).toEqual({ a: 1 })
expect(await loadInput(src('@input.json', '', { 'input.json': '\uFEFF{"b":2}' }))).toEqual({
b: 2,
})
expect(await loadInput(src('@-', '\uFEFF{"c":3}'))).toEqual({ c: 3 })
expect(
await resolveFileRefs(
{ inputs: '@inputs.json' },
REF_SCHEMA,
refs('', { 'inputs.json': '\uFEFF{"value":"inside\\uFEFF"}' }),
),
).toEqual({ inputs: { value: 'inside\uFEFF' } })
})
it('resolves @file and @- only on non-scalar declared fields', async () => {
expect(
await resolveFileRefs(
{ inputs: '@in.json', files: '@-', query: '@keep', other: '@untouched' },
REF_SCHEMA,
refs('[{"b":2}]', { 'in.json': '{"a":1}' }),
),
).toEqual({ inputs: { a: 1 }, files: [{ b: 2 }], query: '@keep', other: '@untouched' })
})
it('an array field takes an array from its file', async () => {
expect(
await resolveFileRefs(
{ files: '@files.json' },
REF_SCHEMA,
refs('', { 'files.json': '[{"c":3}]' }),
),
).toEqual({ files: [{ c: 3 }] })
})
it('reports an unreadable reference as input_invalid', async () => {
await expect(
resolveFileRefs({ inputs: '@missing.json' }, REF_SCHEMA, refs('')),
).rejects.toMatchObject({
code: 'input_invalid',
message: expect.stringContaining('missing.json'),
})
})
it('names the field flag when a reference is not valid JSON', async () => {
await expect(
resolveFileRefs({ files: '@files.json' }, REF_SCHEMA, refs('', { 'files.json': 'nope' })),
).rejects.toMatchObject({
code: 'input_invalid',
message: expect.stringContaining('--files'),
})
})
it('fills pins only for declared, absent fields', () => {
const schema = {
type: 'object',
properties: { workspace_id: { type: 'string' }, page: { type: 'integer' } },
}
expect(applyPins({ page: 2 }, schema, { workspace_id: 'ws-1' })).toEqual({
page: 2,
workspace_id: 'ws-1',
})
expect(applyPins({ workspace_id: 'mine' }, schema, { workspace_id: 'ws-1' })).toEqual({
workspace_id: 'mine',
})
expect(
applyPins({}, { type: 'object', properties: { page: {} } }, { workspace_id: 'ws-1' }),
).toEqual({})
expect(applyPins({}, schema, { workspace_id: null })).toEqual({})
})
+92
View File
@@ -0,0 +1,92 @@
import type { JsonSchema } from '@/plugins/catalog'
import { inputInvalid } from '@/call/errors'
import { CALL_FLAG } from '@/call/flags'
import { errorMessage } from '@/errors/message'
import { isScalar, propertiesOf, shapeOf } from '@/protocol/shape'
import { flagToken } from '@/util/flag-name'
import { isRecord } from '@/util/is-record'
export type InputSource = {
readonly raw: string | undefined
readonly stdin: () => Promise<string>
readonly readFile: (p: string) => Promise<string>
}
export type FileRefSource = Pick<InputSource, 'stdin' | 'readFile'>
/** Text read from an `@…` reference, with the name errors about it should use. */
type Referenced = Readonly<{ text: string; source: string }>
const FILE_PREFIX = '@'
const STDIN_MARKER = '-'
const STDIN_SOURCE = `${FILE_PREFIX}${STDIN_MARKER}`
const INLINE_SOURCE = flagToken(CALL_FLAG.Input)
const STDIN_LABEL = 'stdin'
export function parseJsonValue(raw: string, source: string): unknown {
try {
return JSON.parse(raw.startsWith('\uFEFF') ? raw.slice(1) : raw)
} catch (cause) {
throw inputInvalid(`${source}: not valid JSON (${errorMessage(cause)})`, cause)
}
}
function parseJsonObject(raw: string, source: string): Record<string, unknown> {
const parsed = parseJsonValue(raw, source)
if (!isRecord(parsed)) throw inputInvalid(`${INLINE_SOURCE} must be a JSON object`)
return parsed
}
async function readRef(ref: string, src: FileRefSource): Promise<Referenced> {
if (ref === STDIN_SOURCE) return { text: await src.stdin(), source: STDIN_LABEL }
const path = ref.slice(FILE_PREFIX.length)
try {
return { text: await src.readFile(path), source: path }
} catch (cause) {
throw inputInvalid(`cannot read input file "${path}"`, cause)
}
}
export async function loadInput(src: InputSource): Promise<Record<string, unknown>> {
if (src.raw === undefined) return {}
if (!src.raw.startsWith(FILE_PREFIX)) return parseJsonObject(src.raw, INLINE_SOURCE)
const { text, source } = await readRef(src.raw, src)
return parseJsonObject(text, source)
}
// A non-scalar field typed as a flag keeps its raw `@…` string through the parser,
// which cannot read files; it becomes the referenced JSON only here. Any JSON value will
// do — the field's own schema, not this function, says what shape it must have.
export async function resolveFileRefs(
fields: Record<string, unknown>,
schema: JsonSchema,
src: FileRefSource,
): Promise<Record<string, unknown>> {
const properties = propertiesOf(schema)
const resolved = { ...fields }
for (const [name, value] of Object.entries(fields)) {
const property = properties[name]
if (property === undefined) continue
if (typeof value !== 'string' || !value.startsWith(FILE_PREFIX)) continue
if (isScalar(shapeOf(property))) continue
const { text } = await readRef(value, src)
resolved[name] = parseJsonValue(text, flagToken(name))
}
return resolved
}
export function applyPins(
input: Record<string, unknown>,
schema: JsonSchema,
pins: Readonly<Record<string, string | null>>,
): Record<string, unknown> {
const properties = propertiesOf(schema)
const result = { ...input }
for (const [key, pin] of Object.entries(pins)) {
if (pin === null) continue
if (!(key in properties)) continue
if (key in result) continue
result[key] = pin
}
return result
}
+25
View File
@@ -0,0 +1,25 @@
import type { Printable } from '@/sys/io/view'
import { HttpClientError } from '@/errors/base'
import { ErrorCode } from '@/errors/codes'
const CONTENT_TYPE_HEADER = 'content-type'
const NON_JSON_BODY_PREVIEW_LENGTH = 200
/** The one guard for a response the catalog promised would be JSON. */
export async function parseJsonBody(res: Response): Promise<Printable> {
const text = await res.text()
try {
return JSON.parse(text) as Printable
} catch (cause) {
const contentType = res.headers.get(CONTENT_TYPE_HEADER)
throw new HttpClientError({
code: ErrorCode.ServerError,
message:
contentType !== null
? `response is not JSON (content-type: ${contentType})`
: 'response is not JSON',
cause,
rawResponse: text.slice(0, NON_JSON_BODY_PREVIEW_LENGTH),
})
}
}
@@ -0,0 +1,75 @@
import type { Renderer } from './index'
import { writeFile } from 'node:fs/promises'
import { join, posix } from 'node:path'
import { CALL_FLAG } from '@/call/flags'
import { BaseError, unknownError } from '@/errors/base'
import { ErrorCode } from '@/errors/codes'
import { renderJson } from './object'
const CONTENT_DISPOSITION_HEADER = 'content-disposition'
const CONTENT_TYPE_HEADER = 'content-type'
const UNKNOWN_EXTENSION = 'bin'
const EEXIST = 'EEXIST'
// A name the server picked never replaces a file; a path the caller named does.
const CREATE_ONLY = 'wx'
const CREATE_OR_REPLACE = 'w'
const EXTENSIONS: Readonly<Record<string, string>> = {
'application/json': 'json',
'application/x-yaml': 'yaml',
'application/yaml': 'yaml',
'text/yaml': 'yaml',
'text/csv': 'csv',
'text/plain': 'txt',
'application/zip': 'zip',
'application/pdf': 'pdf',
}
const QUOTED_FILENAME = /filename="([^"]+)"/
const BARE_FILENAME = /filename=([^;]+)/
const NOT_A_FILE_NAME: readonly string[] = ['', '.', '..']
// Only the last part of the server's name is used, so the file stays in the folder.
function baseName(raw: string | undefined): string | undefined {
if (raw === undefined) return undefined
const name = posix.basename(raw.replaceAll('\\', '/'))
return NOT_A_FILE_NAME.includes(name) ? undefined : name
}
function filenameFromContentDisposition(value: string | null): string | undefined {
if (value === null) return undefined
return baseName(QUOTED_FILENAME.exec(value)?.[1] ?? BARE_FILENAME.exec(value)?.[1]?.trim())
}
function extensionOf(contentType: string | null): string {
const mediaType = contentType?.split(';')[0]?.trim().toLowerCase() ?? ''
return EXTENSIONS[mediaType] ?? UNKNOWN_EXTENSION
}
export const fileRenderer: Renderer = async (res, io, options, opId) => {
const bytes = new Uint8Array(await res.arrayBuffer())
const contentType = res.headers.get(CONTENT_TYPE_HEADER)
const filename =
filenameFromContentDisposition(res.headers.get(CONTENT_DISPOSITION_HEADER)) ??
`${opId}.${extensionOf(contentType)}`
const path = options.output ?? join(process.cwd(), filename)
const flag = options.output === undefined ? CREATE_ONLY : CREATE_OR_REPLACE
try {
await writeFile(path, bytes, { flag })
} catch (cause) {
if ((cause as NodeJS.ErrnoException).code === EEXIST)
throw new BaseError({
code: ErrorCode.UsageMissingArg,
message: `${path} already exists; not overwriting it`,
hint: `pass --${CALL_FLAG.Output} <path> to choose where to save it`,
cause,
})
throw unknownError(`failed to write file: ${path}`, cause)
}
// A content type the server never sent is absent, not empty.
const receipt: Record<string, unknown> = { path, size: bytes.byteLength }
if (contentType !== null) receipt.content_type = contentType
return renderJson(io, receipt)
}
@@ -0,0 +1,31 @@
import type { CallFlags } from '@/call/flags'
import type { ExitCodeValue } from '@/errors/codes'
import type { IOService } from '@/plugins/io'
import type { Kind } from '@/protocol/kinds'
import { isKind, KIND } from '@/protocol/kinds'
import { fileRenderer } from './file'
import { listRenderer } from './list'
import { objectRenderer } from './object'
import { sseRenderer } from './sse'
import { textRenderer } from './text'
export type Renderer = (
res: Response,
io: IOService,
flags: CallFlags,
opId: string,
) => Promise<ExitCodeValue>
const RENDERERS: Readonly<Record<Kind, Renderer>> = {
[KIND.Object]: objectRenderer,
[KIND.List]: listRenderer,
[KIND.Sse]: sseRenderer,
[KIND.Text]: textRenderer,
[KIND.File]: fileRenderer,
}
export function rendererFor(kind: string, io: IOService): Renderer {
if (isKind(kind)) return RENDERERS[kind]
io.notice(`unknown kind ${kind}, printing as object`)
return objectRenderer
}
@@ -0,0 +1,6 @@
import type { Renderer } from './index'
import { objectRenderer } from './object'
// A list body (page/limit/total/has_more/data/hints) prints exactly like an
// object body: the parsed JSON re-serialised, indented.
export const listRenderer: Renderer = objectRenderer
@@ -0,0 +1,13 @@
import type { Renderer } from './index'
import type { ExitCodeValue } from '@/errors/codes'
import type { IOService } from '@/plugins/io'
import type { Printable } from '@/sys/io/view'
import { parseJsonBody } from '@/call/json-body'
import { ExitCode } from '@/errors/codes'
export async function renderJson(io: IOService, value: Printable): Promise<ExitCodeValue> {
await io.document(value)
return ExitCode.Success
}
export const objectRenderer: Renderer = async (res, io) => renderJson(io, await parseJsonBody(res))
@@ -0,0 +1,218 @@
import type { CallFlags } from '@/call/flags'
import { Buffer } from 'node:buffer'
import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { expect, it } from 'vite-plus/test'
import { ioService } from '@/plugins/io'
import { bufferStreams } from '@/sys/io/streams'
import { rendererFor } from './index'
const sse = (events: object[]) =>
new Response(events.map((e) => `data: ${JSON.stringify(e)}\n\n`).join(''), {
headers: { 'content-type': 'text/event-stream' },
})
const OP_ID = 'thing.export'
function render(kind: string, res: Response, flags: CallFlags = {}) {
const buf = bufferStreams()
const io = ioService(buf)
return { buf, code: rendererFor(kind, io)(res, io, flags, OP_ID) }
}
it('object and list print the body unchanged, hints included', async () => {
const a = render('object', Response.json({ a: 1 }))
expect(await a.code).toBe(0)
expect(JSON.parse(a.buf.outBuf())).toEqual({ a: 1 })
const body = {
page: 1,
limit: 2,
total: 5,
has_more: true,
data: [],
hints: [{ summary: 'Next page', op: 'x.y', input: { page: 2, limit: 2 } }],
}
const b = render('list', Response.json(body))
await b.code
expect(JSON.parse(b.buf.outBuf())).toEqual(body)
})
it('object rejects a non-JSON body as a server error and writes nothing', async () => {
const res = new Response('<html>', { headers: { 'content-type': 'text/html' } })
const r = render('object', res)
await expect(r.code).rejects.toMatchObject({ code: 'server_error' })
expect(r.buf.outBuf()).toBe('')
})
it('sse folds by default and streams with --stream --only', async () => {
const events = [
{ event: 'message', answer: 'hi' },
{ event: 'node_finished', data: { id: 'n' } },
{ event: 'message_end', message_id: 'm' },
]
const a = render('sse', sse(events))
expect(await a.code).toBe(0)
expect(JSON.parse(a.buf.outBuf())).toMatchObject({
status: 'ended',
text: { answer: 'hi' },
message_id: 'm',
})
const b = render('sse', sse(events), { stream: true, only: ['node_finished'] })
await b.code
expect(
b.buf
.outBuf()
.trim()
.split('\n')
.map((l) => JSON.parse(l)),
).toEqual([{ event: 'node_finished', data: { id: 'n' } }])
})
it('sse exit code follows the fold in both modes', async () => {
const events = [{ event: 'error', message: 'boom', code: 'x' }]
expect(await render('sse', sse(events)).code).toBe(1)
expect(await render('sse', sse(events), { stream: true }).code).toBe(1)
})
it('unknown kind renders as object with one warning line', async () => {
const r = render('hologram', Response.json({ z: 1 }))
expect(await r.code).toBe(0)
expect(r.buf.errBuf()).toMatch(/unknown kind hologram/)
})
it('text writes raw; file writes to --output and prints the receipt', async () => {
const t = render('text', new Response('a: 1\n', { headers: { 'content-type': 'text/plain' } }))
await t.code
expect(t.buf.outBuf()).toBe('a: 1\n')
const dir = mkdtempSync(join(tmpdir(), 'difyctl-file-'))
const out = join(dir, 'x.bin')
const f = render(
'file',
new Response(new Uint8Array([1, 2, 3]), {
headers: {
'content-type': 'application/octet-stream',
'content-disposition': 'attachment; filename="r.bin"',
},
}),
{ output: out },
)
await f.code
expect(readFileSync(out)).toEqual(Buffer.from([1, 2, 3]))
expect(JSON.parse(f.buf.outBuf())).toEqual({
path: out,
size: 3,
content_type: 'application/octet-stream',
})
})
it('file omits content_type when the server sent none', async () => {
const dir = mkdtempSync(join(tmpdir(), 'difyctl-file-'))
const out = join(dir, 'y.bin')
const res = new Response(new Uint8Array([7]))
res.headers.delete('content-type')
const r = render('file', res, { output: out })
await r.code
expect(JSON.parse(r.buf.outBuf())).toEqual({ path: out, size: 1 })
})
it('file names an unnamed download after the op and its content type', async () => {
const dir = mkdtempSync(join(tmpdir(), 'difyctl-file-'))
const cwd = process.cwd()
process.chdir(dir)
const here = process.cwd()
try {
const yaml = render(
'file',
new Response('a: 1', { headers: { 'content-type': 'application/x-yaml' } }),
)
await yaml.code
expect(JSON.parse(yaml.buf.outBuf())).toMatchObject({ path: join(here, `${OP_ID}.yaml`) })
const blob = render(
'file',
new Response(new Uint8Array([1]), { headers: { 'content-type': 'application/vnd.unknown' } }),
)
await blob.code
expect(JSON.parse(blob.buf.outBuf())).toMatchObject({ path: join(here, `${OP_ID}.bin`) })
} finally {
process.chdir(cwd)
}
})
it.each([
['../../escape.txt', 'escape.txt'],
['/etc/passwd', 'passwd'],
['..\\..\\win.txt', 'win.txt'],
['..', `${OP_ID}.txt`],
['dir/', 'dir'],
])('file keeps only the base name of the server filename %s', async (sent, kept) => {
const dir = mkdtempSync(join(tmpdir(), 'difyctl-file-'))
const cwd = process.cwd()
process.chdir(dir)
const here = process.cwd()
try {
const r = render(
'file',
new Response('x', {
headers: {
'content-type': 'text/plain',
'content-disposition': `attachment; filename="${sent}"`,
},
}),
)
await r.code
expect(JSON.parse(r.buf.outBuf())).toMatchObject({ path: join(here, kept) })
expect(readFileSync(join(here, kept), 'utf8')).toBe('x')
} finally {
process.chdir(cwd)
}
})
it('file refuses to overwrite an existing file it named itself, and keeps the old bytes', async () => {
const dir = mkdtempSync(join(tmpdir(), 'difyctl-file-'))
const cwd = process.cwd()
process.chdir(dir)
const here = join(process.cwd(), 'r.txt')
writeFileSync(here, 'old')
try {
const r = render(
'file',
new Response('new', {
headers: {
'content-type': 'text/plain',
'content-disposition': 'attachment; filename="r.txt"',
},
}),
)
await expect(r.code).rejects.toMatchObject({
code: 'usage_missing_arg',
message: `${here} already exists; not overwriting it`,
hint: 'pass --output <path> to choose where to save it',
})
expect(readFileSync(here, 'utf8')).toBe('old')
expect(r.buf.outBuf()).toBe('')
} finally {
process.chdir(cwd)
}
})
it('file overwrites an existing file when --output names it', async () => {
const dir = mkdtempSync(join(tmpdir(), 'difyctl-file-'))
const out = join(dir, 'z.txt')
writeFileSync(out, 'old')
const r = render('file', new Response('new', { headers: { 'content-type': 'text/plain' } }), {
output: out,
})
await r.code
expect(readFileSync(out, 'utf8')).toBe('new')
})
it('file reports other write failures as a failed write, not an existing file', async () => {
const dir = mkdtempSync(join(tmpdir(), 'difyctl-file-'))
const out = join(dir, 'missing', 'z.txt')
const r = render('file', new Response('x'), { output: out })
await expect(r.code).rejects.toMatchObject({
code: 'unknown',
message: `failed to write file: ${out}`,
})
})
+46
View File
@@ -0,0 +1,46 @@
import type { Renderer } from './index'
import { exitCodeFor, finishFold, foldEvent, newFoldResult } from '@/call/fold'
import { parseSSE } from '@/call/sse'
import { normalizeDifyStream } from '@/call/sse-dify'
import { isBrokenPipe } from '@/errors/envelope'
import { errorMessage } from '@/errors/message'
import { isRecord } from '@/util/is-record'
const dec = new TextDecoder()
const STREAM_ENDED_EARLY_PREFIX = 'stream ended early: '
function parseEventData(data: Uint8Array): Record<string, unknown> {
try {
const obj = JSON.parse(dec.decode(data)) as unknown
return isRecord(obj) ? obj : {}
} catch {
return {}
}
}
function matchesOnly(name: string, only: readonly string[] | undefined): boolean {
return only === undefined || only.length === 0 || only.includes(name)
}
// A run that dies mid-stream still folds to whatever arrived: the events already
// seen are real, so they are reported as an `incomplete` result rather than thrown
// away behind a network error.
export const sseRenderer: Renderer = async (res, io, options) => {
const result = newFoldResult()
const stream = options.stream ?? false
if (res.body !== null) {
try {
for await (const ev of normalizeDifyStream(parseSSE(res.body))) {
foldEvent(result, ev.name, parseEventData(ev.data))
if (stream && matchesOnly(ev.name, options.only)) await io.raw(`${dec.decode(ev.data)}\n`)
}
} catch (err) {
if (isBrokenPipe(err)) throw err
io.notice(`${STREAM_ENDED_EARLY_PREFIX}${errorMessage(err)}`)
}
}
if (!stream) await io.document(finishFold(result))
return exitCodeFor(result)
}
@@ -0,0 +1,9 @@
import type { Renderer } from './index'
import { Buffer } from 'node:buffer'
import { ExitCode } from '@/errors/codes'
export const textRenderer: Renderer = async (res, io) => {
const bytes = await res.arrayBuffer()
await io.raw(Buffer.from(bytes))
return ExitCode.Success
}
+178
View File
@@ -0,0 +1,178 @@
import type { FileDeps } from './request'
import type { CatalogOp } from '@/plugins/catalog'
import { readFileSync } from 'node:fs'
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { basename, join } from 'node:path'
import { expect, it } from 'vite-plus/test'
import { LOCAL_FILES } from '@/call/files'
import { parseCatalog } from '@/plugins/catalog'
import { buildRequest } from './request'
const doc = parseCatalog(readFileSync(join(__dirname, '../../test/fixtures/catalog.json')))
const run = doc.ops['run.console_app.workflow']!
const list = doc.ops['get.console_app']!
const readFile = async (p: string) => ({
bytes: new TextEncoder().encode(`bytes-of-${p}`),
name: basename(p),
})
const FOLDERS: Readonly<Record<string, readonly string[]>> = {
'./pkg': ['a.yaml', 's/SKILL.md'],
'./junk': [],
'./brackets': ['x[1].txt'],
}
const isFolder = async (p: string) => p in FOLDERS
const listFolder = async (p: string) => {
const keys = FOLDERS[p]
if (keys === undefined) throw new Error(`not a folder: ${p}`)
return keys
}
const deps: FileDeps = { readFile, isFolder, listFolder }
it('splits path, query and body', async () => {
const req = await buildRequest(list, { workspace_id: 'ws 1', page: 2 }, deps)
expect(req).toMatchObject({
method: 'GET',
path: '/openapi/v1/apps',
query: { workspace_id: 'ws 1', page: '2' },
})
expect(req.json).toBeUndefined()
const post = await buildRequest(
run,
{ app_id: 'a/1', inputs: { q: 'hi' }, workflow_id: 'w' },
deps,
)
expect(post.path).toBe('/openapi/v1/apps/a%2F1/workflow:run')
expect(post.json).toEqual({ inputs: { q: 'hi' }, workflow_id: 'w' })
expect(post.form).toBeUndefined()
})
it('switches to multipart when a file field is present', async () => {
const req = await buildRequest(
run,
{
app_id: 'a1',
inputs: { q: 'x' },
files: { doc: './r.pdf', pages: ['./1.png', './2.png'] },
attachments: ['./att.txt'],
},
deps,
)
expect(req.json).toBeUndefined()
const form = req.form!
expect(form.get('inputs')).toBe('{"q":"x"}')
expect((form.get('files[doc]') as File).name).toBe('r.pdf')
expect(form.getAll('files[pages][]').map((f) => (f as File).name)).toEqual(['1.png', '2.png'])
expect((form.get('attachments[]') as File).name).toBe('att.txt')
})
it('refuses unknown bind values and non-path file values before sending', async () => {
const weird: CatalogOp = { ...run, bind: { ...run.bind, inputs: 'header' } }
await expect(buildRequest(weird, { app_id: 'a', inputs: {} }, deps)).rejects.toMatchObject({
code: 'input_invalid',
message: expect.stringContaining('header'),
})
await expect(
buildRequest(run, { app_id: 'a', inputs: {}, files: { doc: 42 } }, deps),
).rejects.toMatchObject({ code: 'input_invalid' })
})
it('expands a folder into one part per file', async () => {
const req = await buildRequest(run, { app_id: 'a', inputs: {}, attachments: './pkg' }, deps)
const form = req.form!
expect([...form.keys()]).toEqual(['inputs', 'attachments[a.yaml]', 'attachments[s/SKILL.md]'])
expect((form.get('attachments[a.yaml]') as File).name).toBe('a.yaml')
expect((form.get('attachments[s/SKILL.md]') as File).name).toBe('SKILL.md')
})
it('refuses a folder inside a list or a map', async () => {
await expect(
buildRequest(run, { app_id: 'a', inputs: {}, files: { doc: './pkg' } }, deps),
).rejects.toMatchObject({
code: 'input_invalid',
message: '"./pkg" is a folder; a folder can only be the whole value of files',
})
await expect(
buildRequest(run, { app_id: 'a', inputs: {}, attachments: ['./pkg'] }, deps),
).rejects.toMatchObject({
code: 'input_invalid',
message: expect.stringContaining('is a folder'),
})
await expect(
buildRequest(run, { app_id: 'a', inputs: {}, attachments: ['./junk'] }, deps),
).rejects.toMatchObject({ message: expect.stringContaining('is a folder') })
})
it('refuses an empty folder', async () => {
await expect(
buildRequest(run, { app_id: 'a', inputs: {}, attachments: './junk' }, deps),
).rejects.toMatchObject({
code: 'input_invalid',
message: expect.stringContaining('folder "./junk" has no files'),
})
})
it('refuses a bracket in a folder path', async () => {
await expect(
buildRequest(run, { app_id: 'a', inputs: {}, attachments: './brackets' }, deps),
).rejects.toMatchObject({
code: 'input_invalid',
message: expect.stringContaining('x[1].txt'),
})
})
it('keeps the missing-path error when the path is not a folder', async () => {
const failing = async () => {
throw new Error('ENOENT')
}
await expect(
buildRequest(
run,
{ app_id: 'a', inputs: {}, attachments: './nope' },
{ ...deps, readFile: failing },
),
).rejects.toMatchObject({
code: 'input_invalid',
message: 'cannot read file "./nope"',
})
})
it('lists a folder only when it is the whole value', async () => {
const checked: string[] = []
const listed: string[] = []
const counting: FileDeps = {
readFile,
isFolder: async (p) => {
checked.push(p)
return isFolder(p)
},
listFolder: async (p) => {
listed.push(p)
return listFolder(p)
},
}
await buildRequest(run, { app_id: 'a', inputs: {}, attachments: './att.txt' }, counting)
await expect(
buildRequest(run, { app_id: 'a', inputs: {}, attachments: ['./pkg'] }, counting),
).rejects.toMatchObject({ message: expect.stringContaining('is a folder') })
expect(checked).toEqual(['./att.txt', './pkg'])
expect(listed).toEqual([])
})
it('sends a real folder through the local file deps', async () => {
const root = await mkdtemp(join(tmpdir(), 'difyctl-request-'))
try {
await writeFile(join(root, 'a.yaml'), 'app: 1')
await mkdir(join(root, 's'))
await writeFile(join(root, 's', 'SKILL.md'), '# skill')
const req = await buildRequest(run, { app_id: 'a', inputs: {}, attachments: root }, LOCAL_FILES)
const form = req.form!
expect([...form.keys()]).toEqual(['inputs', 'attachments[a.yaml]', 'attachments[s/SKILL.md]'])
const yaml = form.get('attachments[a.yaml]') as File
const skill = form.get('attachments[s/SKILL.md]') as File
expect([yaml.name, skill.name]).toEqual(['a.yaml', 'SKILL.md'])
expect([await yaml.text(), await skill.text()]).toEqual(['app: 1', '# skill'])
} finally {
await rm(root, { recursive: true, force: true })
}
})
+230
View File
@@ -0,0 +1,230 @@
import type { CatalogOp } from '@/plugins/catalog'
import type { HttpRequest } from '@/plugins/http'
import type { Bind } from '@/protocol/bind'
import { join } from 'node:path'
import { inputInvalid } from '@/call/errors'
import { BIND, isBind } from '@/protocol/bind'
import { isRecord } from '@/util/is-record'
export type FileReader = (
path: string,
) => Promise<{ readonly bytes: Uint8Array<ArrayBuffer>; readonly name: string }>
export type FolderCheck = (path: string) => Promise<boolean>
export type FolderLister = (path: string) => Promise<readonly string[]>
export type FileDeps = {
readonly readFile: FileReader
readonly isFolder: FolderCheck
readonly listFolder: FolderLister
}
const LIST_SUFFIX = '[]'
const RESERVED_KEY_CHARS = /[[\]]/
const HttpMethod = { Get: 'GET', Delete: 'DELETE' } as const
const BODYLESS_METHODS: ReadonlySet<string> = new Set(Object.values(HttpMethod))
const Placement = { Path: 'path', Query: 'query', Body: 'body', File: 'file' } as const
type PlacementValue = (typeof Placement)[keyof typeof Placement]
const BIND_PLACEMENT: Readonly<Record<Bind, PlacementValue>> = {
[BIND.Path]: Placement.Path,
[BIND.Query]: Placement.Query,
[BIND.Body]: Placement.Body,
[BIND.File]: Placement.File,
}
type Buckets = Readonly<Record<PlacementValue, Map<string, unknown>>>
function defaultPlacement(method: string): PlacementValue {
return BODYLESS_METHODS.has(method) ? Placement.Query : Placement.Body
}
// Every input key is placed before anything else is built: an unsupported bind
// value must fail before a byte of the request exists.
function classify(op: CatalogOp, input: Record<string, unknown>): Buckets {
const buckets: Buckets = {
[Placement.Path]: new Map(),
[Placement.Query]: new Map(),
[Placement.Body]: new Map(),
[Placement.File]: new Map(),
}
const fallback = defaultPlacement(op.method)
for (const [key, value] of Object.entries(input)) {
const bindValue = op.bind[key]
if (bindValue === undefined) {
buckets[fallback].set(key, value)
continue
}
if (!isBind(bindValue))
throw inputInvalid(`bind value ${bindValue} for ${key} is not supported by this difyctl`)
buckets[BIND_PLACEMENT[bindValue]].set(key, value)
}
return buckets
}
function substitutePath(path: string, values: Map<string, unknown>): string {
return path.replace(/\{([^{}]+)\}/g, (placeholder, name: string) =>
values.has(name) ? encodeURIComponent(String(values.get(name))) : placeholder,
)
}
function toQueryValue(value: unknown): string | readonly string[] | undefined {
if (value === null || value === undefined) return undefined
if (Array.isArray(value)) return value.map((item) => String(item))
return String(value)
}
function buildQuery(values: Map<string, unknown>): HttpRequest['query'] {
const query: Record<string, string | readonly string[]> = {}
for (const [key, value] of values) {
const converted = toQueryValue(value)
if (converted !== undefined) query[key] = converted
}
return Object.keys(query).length === 0 ? undefined : query
}
function buildBodyObject(values: Map<string, unknown>): Record<string, unknown> {
const body: Record<string, unknown> = {}
for (const [key, value] of values) {
if (value === undefined) continue
body[key] = value
}
return body
}
function partName(field: string, key: string | undefined, many: boolean): string {
const base = key === undefined ? field : `${field}[${key}]`
return many ? `${base}${LIST_SUFFIX}` : base
}
async function readAsFile(path: string, { readFile }: FileDeps): Promise<File> {
let resolved: Awaited<ReturnType<FileReader>>
try {
resolved = await readFile(path)
} catch (cause) {
throw inputInvalid(`cannot read file "${path}"`, cause)
}
return new File([resolved.bytes], resolved.name)
}
function assertPathString(value: unknown, field: string): asserts value is string {
if (typeof value !== 'string')
throw inputInvalid(
`file field "${field}" must be a path string, a folder, an array of paths, or an object mapping names to paths`,
)
}
async function assertNotFolder(path: string, field: string, deps: FileDeps): Promise<void> {
if (await deps.isFolder(path))
throw inputInvalid(`"${path}" is a folder; a folder can only be the whole value of ${field}`)
}
type FieldTarget = {
readonly form: FormData
// Top-level input key bound to `file`.
readonly field: string
readonly deps: FileDeps
}
type FolderParts = FieldTarget & {
readonly folder: string
// File paths relative to `folder`, as returned by `listFolder`.
readonly keys: readonly string[]
}
type FileParts = FieldTarget & {
// Multipart part name, e.g. `field`, `field[]`, `field[key]`, `field[key][]`.
readonly name: string
// A path string or an array of path strings; validated per item.
readonly value: unknown
// Input location for error messages, e.g. `field` or `field.key`.
readonly label: string
}
async function appendFolderParts({ form, field, deps, folder, keys }: FolderParts): Promise<void> {
if (keys.length === 0) throw inputInvalid(`folder "${folder}" has no files`)
const reserved = keys.find((key) => RESERVED_KEY_CHARS.test(key))
if (reserved !== undefined)
throw inputInvalid(
`"${reserved}" in folder "${folder}" contains "[" or "]", which a part name cannot carry`,
)
for (const key of keys)
form.append(partName(field, key, false), await readAsFile(join(folder, key), deps))
}
async function appendFileParts({
form,
field,
deps,
name,
value,
label,
}: FileParts): Promise<void> {
const items = Array.isArray(value) ? value : [value]
for (const item of items) {
assertPathString(item, label)
await assertNotFolder(item, field, deps)
form.append(name, await readAsFile(item, deps))
}
}
async function appendFileField(target: FieldTarget, value: unknown): Promise<void> {
const { form, field, deps } = target
if (value === null || value === undefined) return
if (typeof value === 'string') {
if (await deps.isFolder(value))
return appendFolderParts({ ...target, folder: value, keys: await deps.listFolder(value) })
form.append(partName(field, undefined, false), await readAsFile(value, deps))
return
}
if (isRecord(value)) {
for (const [key, item] of Object.entries(value))
await appendFileParts({
...target,
name: partName(field, key, Array.isArray(item)),
value: item,
label: `${field}.${key}`,
})
return
}
await appendFileParts({
...target,
name: partName(field, undefined, Array.isArray(value)),
value,
label: field,
})
}
function hasFileValue(values: Map<string, unknown>): boolean {
return [...values.values()].some((value) => value !== null && value !== undefined)
}
export async function buildRequest(
op: CatalogOp,
input: Record<string, unknown>,
deps: FileDeps,
): Promise<HttpRequest> {
const buckets = classify(op, input)
const path = substitutePath(op.path, buckets[Placement.Path])
const query = buildQuery(buckets[Placement.Query])
if (!hasFileValue(buckets[Placement.File])) {
const bodyObj = buildBodyObject(buckets[Placement.Body])
const isEmptyBodylessRequest =
BODYLESS_METHODS.has(op.method) && Object.keys(bodyObj).length === 0
return { method: op.method, path, query, json: isEmptyBodylessRequest ? undefined : bodyObj }
}
const form = new FormData()
for (const [key, value] of buckets[Placement.Body]) {
if (value === undefined) continue
form.append(key, JSON.stringify(value))
}
for (const [field, value] of buckets[Placement.File])
await appendFileField({ form, field, deps }, value)
return { method: op.method, path, query, form }
}
@@ -0,0 +1,99 @@
import type { SseEvent } from './sse'
import { describe, expect, it } from 'vite-plus/test'
import { eventNameFromDifyData, normalizeDifyStream } from './sse-dify'
const enc = new TextEncoder()
function bytes(s: string): Uint8Array {
return enc.encode(s)
}
async function* fromArray(events: SseEvent[]): AsyncGenerator<SseEvent, void, void> {
for (const ev of events) yield ev
}
async function collect(iter: AsyncIterable<SseEvent>): Promise<SseEvent[]> {
const out: SseEvent[] = []
for await (const ev of iter) out.push(ev)
return out
}
describe('eventNameFromDifyData', () => {
it('returns empty string for zero-byte data', () => {
expect(eventNameFromDifyData(new Uint8Array())).toBe('')
})
it('returns embedded event name for object payload', () => {
expect(eventNameFromDifyData(bytes('{"event":"message","answer":"hi"}'))).toBe('message')
})
it('returns empty string for malformed JSON', () => {
expect(eventNameFromDifyData(bytes('not-json'))).toBe('')
})
it('returns empty string for non-string event field', () => {
expect(eventNameFromDifyData(bytes('{"event":42}'))).toBe('')
})
it('returns empty string for null payload', () => {
expect(eventNameFromDifyData(bytes('null'))).toBe('')
})
it('returns empty string for non-object JSON values', () => {
expect(eventNameFromDifyData(bytes('"just a string"'))).toBe('')
expect(eventNameFromDifyData(bytes('123'))).toBe('')
expect(eventNameFromDifyData(bytes('true'))).toBe('')
})
it('returns empty string for object missing event key', () => {
expect(eventNameFromDifyData(bytes('{"answer":"hi"}'))).toBe('')
})
})
describe('normalizeDifyStream', () => {
it('promotes JSON event field into ev.name when transport name absent', async () => {
const out = await collect(
normalizeDifyStream(
fromArray([
{ name: '', data: bytes('{"event":"workflow_started","id":"wf-1"}') },
{ name: '', data: bytes('{"event":"workflow_finished","status":"succeeded"}') },
]),
),
)
expect(out.map((e) => e.name)).toEqual(['workflow_started', 'workflow_finished'])
})
it('preserves transport-level event name over JSON event field', async () => {
const out = await collect(
normalizeDifyStream(
fromArray([
{ name: 'ping', data: bytes('') },
{ name: 'foo', data: bytes('{"event":"bar"}') },
]),
),
)
expect(out.map((e) => e.name)).toEqual(['ping', 'foo'])
})
it('forwards unchanged when ev.name absent and data has no JSON event field', async () => {
const ev: SseEvent = { name: '', data: bytes('{"answer":"hi"}') }
const out = await collect(normalizeDifyStream(fromArray([ev])))
expect(out).toHaveLength(1)
expect(out[0]?.name).toBe('')
expect(out[0]?.data).toBe(ev.data)
})
it('forwards unchanged when data is malformed JSON', async () => {
const out = await collect(
normalizeDifyStream(fromArray([{ name: '', data: bytes('not-json') }])),
)
expect(out).toHaveLength(1)
expect(out[0]?.name).toBe('')
})
it('forwards empty-data events with empty name', async () => {
const out = await collect(normalizeDifyStream(fromArray([{ name: '', data: bytes('') }])))
expect(out).toHaveLength(1)
expect(out[0]?.name).toBe('')
})
})
+33
View File
@@ -0,0 +1,33 @@
import type { SseEvent } from './sse'
const dec = new TextDecoder()
export function eventNameFromDifyData(data: Uint8Array): string {
if (data.byteLength === 0) return ''
try {
const obj = JSON.parse(dec.decode(data)) as unknown
if (obj === null || typeof obj !== 'object') return ''
const evt = (obj as { event?: unknown }).event
return typeof evt === 'string' ? evt : ''
} catch {
return ''
}
}
// Dify always sends JSON-encoded SSE data. Most endpoints embed the event
// name in the JSON `event` field rather than emitting a transport-level
// `event:` line. This adapter promotes the embedded name into `ev.name`
// so consumers can dispatch uniformly. Transport-level `event:` lines win
// when both are present, preserving compatibility with `event: ping`.
export async function* normalizeDifyStream(
iter: AsyncIterable<SseEvent>,
): AsyncGenerator<SseEvent, void, void> {
for await (const ev of iter) {
if (ev.name !== '') {
yield ev
continue
}
const name = eventNameFromDifyData(ev.data)
yield name === '' ? ev : { ...ev, name }
}
}
+132
View File
@@ -0,0 +1,132 @@
import { execFile } from 'node:child_process'
import { promisify } from 'node:util'
import { describe, expect, it } from 'vite-plus/test'
import { parseSSE } from './sse'
function streamOf(...chunks: string[]): ReadableStream<Uint8Array> {
const enc = new TextEncoder()
return new ReadableStream({
start(c) {
for (const ch of chunks) c.enqueue(enc.encode(ch))
c.close()
},
})
}
async function collect(
s: ReadableStream<Uint8Array>,
): Promise<{ name: string; data: string; id?: string }[]> {
const out: { name: string; data: string; id?: string }[] = []
const dec = new TextDecoder()
for await (const ev of parseSSE(s))
out.push({ name: ev.name, data: dec.decode(ev.data), id: ev.id })
return out
}
describe('parseSSE', () => {
it('emits one event per blank-line-terminated record', async () => {
const s = streamOf('event: message\ndata: hello\n\nevent: ping\ndata: \n\n')
const got = await collect(s)
expect(got).toEqual([
{ name: 'message', data: 'hello', id: undefined },
{ name: 'ping', data: '', id: undefined },
])
})
it('joins multi-line data with newlines', async () => {
const s = streamOf('event: message\ndata: line1\ndata: line2\n\n')
const got = await collect(s)
expect(got[0]?.data).toBe('line1\nline2')
})
it('propagates id field', async () => {
const s = streamOf('id: 42\nevent: m\ndata: x\n\n')
expect((await collect(s))[0]?.id).toBe('42')
})
it('skips comment lines', async () => {
const s = streamOf(': comment\nevent: m\ndata: x\n\n')
expect(await collect(s)).toEqual([{ name: 'm', data: 'x', id: undefined }])
})
it('survives chunk boundaries inside a field', async () => {
const s = streamOf('event: mes', 'sage\nda', 'ta: hel', 'lo\n\n')
expect((await collect(s))[0]).toEqual({ name: 'message', data: 'hello', id: undefined })
})
it('handles multi-byte utf-8 split across chunks', async () => {
const enc = new TextEncoder().encode('event: m\ndata: 😀\n\n')
const a = enc.slice(0, 14)
const b = enc.slice(14)
const s = new ReadableStream<Uint8Array>({
start(c) {
c.enqueue(a)
c.enqueue(b)
c.close()
},
})
expect((await collect(s))[0]?.data).toBe('😀')
})
it('propagates a response body error to the consumer', async () => {
const error = new Error('network disconnected')
const body = new ReadableStream<Uint8Array>({
start(controller) {
controller.error(error)
},
})
await expect(collect(body)).rejects.toBe(error)
})
it('observes read failures while the consumer is processing a yielded event', async () => {
// Isolate Node's strict unhandled-rejection policy from the test runner.
const source = new URL('./sse.ts', import.meta.url).href
const script = `
import assert from 'node:assert/strict'
import { setImmediate } from 'node:timers/promises'
import { parseSSE } from ${JSON.stringify(source)}
let controller
const body = new ReadableStream({ start(c) { controller = c } })
const events = parseSSE(body)
controller.enqueue(new TextEncoder().encode('data: first\\n\\ndata: second\\n\\n'))
const decoder = new TextDecoder()
assert.equal(decoder.decode((await events.next()).value.data), 'first')
const error = new Error('network disconnected')
controller.error(error)
await setImmediate()
assert.equal(decoder.decode((await events.next()).value.data), 'second')
await assert.rejects(events.next(), (failure) => failure === error)
console.log('stream error reached the consumer')
`
const { stdout, stderr } = await promisify(execFile)(process.execPath, [
'--unhandled-rejections=strict',
'--input-type=module',
'-e',
script,
])
expect(stdout.trim()).toBe('stream error reached the consumer')
expect(stderr).toBe('')
})
it('aborts when signal fires', async () => {
const ctrl = new AbortController()
const slow = new ReadableStream<Uint8Array>({
pull(c) {
c.enqueue(new TextEncoder().encode('event: m\ndata: x\n\n'))
},
})
let seen = 0
let caught: unknown
try {
for await (const _ of parseSSE(slow, ctrl.signal)) {
seen++
if (seen === 1) ctrl.abort()
}
} catch (e) {
caught = e
}
expect(seen).toBeGreaterThanOrEqual(1)
expect(seen).toBeLessThan(50)
expect((caught as Error).name).toBe('AbortError')
})
})
+102
View File
@@ -0,0 +1,102 @@
import { createParser } from 'eventsource-parser'
export type SseEvent = {
name: string
data: Uint8Array
id?: string
}
export async function* parseSSE(
body: ReadableStream<Uint8Array>,
signal?: AbortSignal,
): AsyncGenerator<SseEvent, void, void> {
const queue: SseEvent[] = []
let resolveNext: (() => void) | undefined
let pendingWake = false
let done = false
const wake = (): void => {
pendingWake = true
if (resolveNext !== undefined) {
const r = resolveNext
resolveNext = undefined
r()
}
}
const enc = new TextEncoder()
const parser = createParser({
onEvent(ev) {
queue.push({
name: ev.event ?? '',
data: enc.encode(ev.data),
id: ev.id,
})
wake()
},
})
const reader = body.getReader()
const dec = new TextDecoder('utf-8')
const onAbort = (): void => {
reader.cancel().catch(() => {})
}
if (signal !== undefined) {
if (signal.aborted) onAbort()
else signal.addEventListener('abort', onAbort, { once: true })
}
const pump = (async () => {
try {
while (true) {
if (signal?.aborted) {
const e = new Error('aborted')
e.name = 'AbortError'
throw e
}
const { value, done: rDone } = await reader.read()
if (rDone) break
parser.feed(dec.decode(value, { stream: true }))
}
} finally {
done = true
wake()
try {
reader.releaseLock()
} catch {}
}
})()
// Observe background failures even while a yielded event suspends the consumer.
// Awaiting the original pump below still propagates the error after the queue drains.
void pump.catch(() => {})
try {
while (true) {
while (queue.length > 0) {
const ev = queue.shift()
if (ev !== undefined) yield ev
}
if (done) {
await pump
return
}
if (pendingWake) {
pendingWake = false
continue
}
await new Promise<void>((res) => {
resolveNext = res
})
pendingWake = false
}
} finally {
if (signal !== undefined) signal.removeEventListener('abort', onAbort)
if (!done) {
try {
await reader.cancel()
} catch {}
}
}
}
@@ -0,0 +1,38 @@
import { readFileSync } from 'node:fs'
import { join } from 'node:path'
import { expect, it } from 'vite-plus/test'
import { parseCatalog } from '@/plugins/catalog'
import { validateInput } from './validate'
const doc = parseCatalog(readFileSync(join(__dirname, '../../test/fixtures/catalog.json')))
const run = doc.ops['run.console_app.workflow']!.input
const list = doc.ops['get.console_app']!.input
it('returns no details for valid input against the real schemas', () => {
expect(
validateInput(run, { app_id: 'a', inputs: {}, files: { doc: './r.pdf', pages: ['1.png'] } }),
).toEqual([])
expect(validateInput(list, { workspace_id: 'not-a-uuid', limit: 5 })).toEqual([]) // formats are the server's job
})
it('reports missing required, wrong types and bad enums in the 422 detail shape', () => {
expect(validateInput(run, { inputs: 'x' })).toContainEqual({
type: 'required',
loc: ['app_id'],
msg: expect.stringContaining('required'),
})
expect(validateInput(run, { app_id: 'a', inputs: 'x' })).toContainEqual({
type: 'type',
loc: ['inputs'],
msg: expect.stringContaining('object'),
})
expect(validateInput(list, { workspace_id: 'w', mode: 'agent' })).toContainEqual({
type: 'enum',
loc: ['mode'],
msg: expect.stringContaining('allowed'),
})
})
it('lets unknown keys through to the server', () => {
expect(validateInput(run, { app_id: 'a', inputs: {}, extra: 1 })).toEqual([])
})
+45
View File
@@ -0,0 +1,45 @@
import type { ErrorObject, ValidateFunction } from 'ajv/dist/2020'
import type { JsonSchema } from '@/plugins/catalog'
import Ajv2020 from 'ajv/dist/2020'
export type ValidationDetail = {
readonly type: string
readonly loc: (string | number)[]
readonly msg: string
}
// One shared Ajv instance: schemas come from a trusted, already-parsed catalog, so
// $data is never enabled and formats are left to the server (validateFormats: false).
const ajv = new Ajv2020({ allErrors: true, strict: false, validateFormats: false })
const compiled = new WeakMap<JsonSchema, ValidateFunction>()
function compile(schema: JsonSchema): ValidateFunction {
const cached = compiled.get(schema)
if (cached !== undefined) return cached
const validate = ajv.compile(schema)
compiled.set(schema, validate)
return validate
}
const INSTANCE_PATH_SEPARATOR = '/'
// Errors that name a field: the ajv param holding the name, and the message to show.
const FIELD_ERRORS: Readonly<Record<string, Readonly<{ param: string; msg: string }>>> = {
required: { param: 'missingProperty', msg: 'required' },
additionalProperties: { param: 'additionalProperty', msg: 'unknown field' },
}
function toDetail(error: ErrorObject): ValidationDetail {
const reading = FIELD_ERRORS[error.keyword]
const loc: (string | number)[] = error.instancePath.split(INSTANCE_PATH_SEPARATOR).filter(Boolean)
const named =
reading === undefined ? undefined : (error.params as Record<string, unknown>)[reading.param]
if (typeof named === 'string') loc.push(named)
return { type: error.keyword, loc, msg: reading?.msg ?? error.message ?? error.keyword }
}
export function validateInput(schema: JsonSchema, input: unknown): readonly ValidationDetail[] {
const validate = compile(schema)
if (validate(input) || validate.errors == null) return []
return validate.errors.map(toDetail)
}
+74
View File
@@ -0,0 +1,74 @@
# AGENTS.md — `src/commands/`
Per-command agent-optimized usage and structure guide.
## Command folder convention
Every command is a folder. `index.ts` is the command class file. All related
code — business logic, helpers, tests — colocates inside the folder.
Subcommands are subfolders.
```
src/commands/
<topic>/
<verb>/
index.ts ← command class (extends Command; the ONLY file the registry discovers)
helpers.ts ← optional behavior owner (not a command, invisible to the registry)
*.test.ts ← tests
<nested-verb>/ ← subcommand (e.g. ops/describe/)
index.ts
_shared/ ← intra-topic shared code (only when needed by 2+ siblings)
<shared>.ts
```
The registry generator (`pnpm tree:gen` → `src/commands/tree.generated.ts`) discovers
commands only via `**/index.+(js|cjs|mjs|ts)`. All other files in command
folders are invisible to the registry — add freely without glob exclusions.
Folders prefixed with `_` are excluded from registry discovery.
The command class extends `Command<typeof INPUT>` (`src/plugins/commands/command.ts`):
```ts
export default class MyCmd extends Command<typeof INPUT> {
static override summary = 'One-line description'
static override effect = 'write' as const // 'read' (default) | 'write' | 'destructive'
static override input = INPUT // a Zod object; also the argv parser's schema
static override positional = ['id'] as const // optional; maps positional argv to input keys
static override examples = [{ title: '...', input: { id: '...' } }] // optional
static override hidden = true // optional; keeps the command out of help, not out of the tree
async run(input: z.infer<typeof INPUT>, ctx: CommandContext) {
// read plugin services with ctx.get(...); the return value is printed as
// indented JSON. Return an Outcome for a non-zero exit or output already
// written through ctx.get(io); notices go to ctx.get(io).notice(...).
}
}
```
`schema()` is the JSON Schema help documents and `finalize` validates, derived from
`input`; `flags()` is what the argv parser accepts (default: `schema()`);
`facets()` is the op half of the descriptor (default: none); `finalize(input, path)`
is the one input gate, throwing `input_invalid` and then applying the Zod defaults.
Only the catalog-op adapter overrides them.
`run`'s return value is the JSON value printed to stdout; there is no separate
output-formatting step and no `agentGuide` — `--help` on any command prints the
same descriptor (`summary`, `effect`, `input`, `positional`, `examples`, plus
`kind`, `bind`, `pins` for a catalog operation) that `difyctl help <id>` prints.
## Adding a new command
1. Create `src/commands/<topic>/<verb>/index.ts` extending `Command`.
1. Keep small owner-local behavior in `index.ts`; extract a sibling module when logic needs independent tests, reuse, or a clearer owner.
1. Run `pnpm tree:gen` to regenerate the command tree (also runs implicitly via `prebuild`/`predev`/`pretest`).
1. Run `pnpm test` to verify coverage.
## Shared utilities
Code used by two or more commands lives in a top-level domain folder (e.g.
`src/call/`, `src/errors/`) or on a plugin service, never inside a
command folder. One command never imports from another command's folder.
A command imports a plugin through `@/plugins/<name>` and reads it with
`ctx.get(...)`. The framework files are the exception:
`plugins/commands/{command,cancel,registry}.ts` and `plugins/argv/parse.ts`.
@@ -0,0 +1,31 @@
import type { TestWorld } from '@test/fixtures/kernel'
import { testContext } from '@test/fixtures/kernel'
import { afterEach, expect, it } from 'vite-plus/test'
import { catalog } from '@/plugins/catalog'
import { commands } from '@/plugins/commands'
const worlds: TestWorld[] = []
afterEach(async () => {
for (const w of worlds.splice(0)) await w.stop()
})
it('deletes the cached catalog file', async () => {
const w = await testContext({ login: true, argv: ['refresh', 'cache'] })
worlds.push(w)
await (await w.ctx.get(commands)).run()
expect((await w.ctx.get(catalog)).loaded).toBe(true)
const w2 = await testContext({ login: true, argv: ['delete', 'cache'], reuseDirOf: w })
worlds.push(w2)
expect(await (await w2.ctx.get(commands)).run()).toBe(0)
expect(JSON.parse(w2.io.outBuf())).toEqual({ cleared: true })
expect((await w2.ctx.get(catalog)).loaded).toBe(false)
})
it('rejects with exit 4 when not logged in', async () => {
const w = await testContext({ login: false, argv: ['delete', 'cache'] })
worlds.push(w)
await expect((await w.ctx.get(commands)).run()).rejects.toMatchObject({
code: 'not_logged_in',
})
})
+18
View File
@@ -0,0 +1,18 @@
import type { CommandContext } from '@/plugins/base'
import { z } from 'zod'
import { catalog } from '@/plugins/catalog'
import { Command } from '@/plugins/commands/command'
const INPUT = z.object({})
export default class CacheClear extends Command<typeof INPUT> {
static override summary = 'Delete the local server catalog cache'
static override effect = 'write' as const
static override input = INPUT
async run(_input: z.infer<typeof INPUT>, ctx: CommandContext) {
const catalogService = await ctx.get(catalog)
await catalogService.clear()
return { cleared: true }
}
}
@@ -0,0 +1,35 @@
import type { TestWorld } from '@test/fixtures/kernel'
import { testContext } from '@test/fixtures/kernel'
import { afterEach, expect, it } from 'vite-plus/test'
import { commands } from '@/plugins/commands'
import { config } from '@/plugins/config'
const worlds: TestWorld[] = []
afterEach(async () => {
for (const w of worlds.splice(0)) await w.stop()
})
it('reads a value written directly through the config service', async () => {
const w = await testContext({ login: false, argv: ['get', 'config', 'http.timeout'] })
worlds.push(w)
await (await w.ctx.get(config)).set('http.timeout', '5000')
expect(await (await w.ctx.get(commands)).run()).toBe(0)
expect(JSON.parse(w.io.outBuf())).toBe(5000)
})
it('prints the whole doc with its path when no key is given', async () => {
const w = await testContext({ login: false, argv: ['get', 'config'] })
worlds.push(w)
expect(await (await w.ctx.get(commands)).run()).toBe(0)
const body = JSON.parse(w.io.outBuf()) as { path: string; http: { timeout: number } }
expect(body.http.timeout).toBe(30_000)
expect(body.path).toContain('config.yml')
})
it('rejects an unknown key with exit 2', async () => {
const w = await testContext({ login: false, argv: ['get', 'config', 'nope'] })
worlds.push(w)
await expect((await w.ctx.get(commands)).run()).rejects.toMatchObject({
code: 'config_invalid_key',
})
})
@@ -0,0 +1,17 @@
import type { CommandContext } from '@/plugins/base'
import { z } from 'zod'
import { Command } from '@/plugins/commands/command'
import { config } from '@/plugins/config'
const INPUT = z.object({ key: z.string().optional() })
export default class ConfigGet extends Command<typeof INPUT> {
static override summary = 'Print the local config, or one key'
static override input = INPUT
static override positional = ['key'] as const
async run(input: z.infer<typeof INPUT>, ctx: CommandContext) {
const configService = await ctx.get(config)
return configService.get(input.key)
}
}
@@ -0,0 +1,24 @@
import type { TestWorld } from '@test/fixtures/kernel'
import { readFile } from 'node:fs/promises'
import { join } from 'node:path'
import { testContext } from '@test/fixtures/kernel'
import { afterEach, expect, it } from 'vite-plus/test'
import { commands } from '@/plugins/commands'
const worlds: TestWorld[] = []
afterEach(async () => {
for (const w of worlds.splice(0)) await w.stop()
})
it('writes the difyctl skill into the given skills root', async () => {
const seed = await testContext({ login: false })
worlds.push(seed)
const dir = join(seed.dir, 'target')
const argv = ['install', 'skills', dir]
const w = await testContext({ login: false, argv, reuseDirOf: seed })
worlds.push(w)
expect(await (await w.ctx.get(commands)).run()).toBe(0)
const body = JSON.parse(w.io.outBuf()) as { wrote: string[] }
expect(body.wrote).toContain(join(dir, 'difyctl', 'SKILL.md'))
expect(await readFile(join(dir, 'difyctl', 'SKILL.md'), 'utf8')).toContain('name: difyctl')
})
@@ -0,0 +1,27 @@
import { resolve } from 'node:path'
import { z } from 'zod'
import { Command } from '@/plugins/commands/command'
import { installSkill } from '@/skills/install'
import { FROM_FIELD, openSource } from '@/skills/source'
const INPUT = z.object({
dir: z
.string()
.min(1)
.describe("The agent's skills root: the folder that holds one subfolder per skill"),
from: FROM_FIELD,
})
export default class SkillsInstall extends Command<typeof INPUT> {
static override summary = 'Write the difyctl skill into a skills root'
static override effect = 'write' as const
static override input = INPUT
static override positional = ['dir'] as const
static override examples = [
{ title: 'Install the skill for Claude Code', input: { dir: '~/.claude/skills' } },
]
async run(input: z.infer<typeof INPUT>) {
return { wrote: await installSkill(resolve(input.dir), await openSource(input.from)) }
}
}
@@ -0,0 +1,261 @@
import type { TestWorld } from '@test/fixtures/kernel'
import { existsSync, readFileSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
import { testContext } from '@test/fixtures/kernel'
import { afterEach, expect, it } from 'vite-plus/test'
import { PENDING_FILE_NAME } from '@/auth/pending-login'
import { Context } from '@/kernel/context'
import { commands } from '@/plugins/commands'
import { session } from '@/plugins/session'
import { token } from '@/plugins/token'
const worlds: TestWorld[] = []
afterEach(async () => {
for (const w of worlds.splice(0)) await w.stop()
})
it('logs the previous login out, runs the device flow, saves the pin and the token', async () => {
const seed = await testContext({ login: true })
worlds.push(seed)
const w = await testContext({
login: true,
argv: ['login', '--server', seed.mock.url, '--no-browser', '--no-keyring', '--insecure'],
reuseDirOf: seed,
})
worlds.push(w)
expect(await (await w.ctx.get(commands)).run()).toBe(0)
expect(w.io.errBuf()).toMatch(/logged out me@x from/)
expect(w.io.errBuf()).toMatch(/code ABCD-1234/)
const login = await (await w.ctx.get(session)).current()
expect(login?.workspaceId).toBe('ws-1')
expect(login?.tokenStorage).toBe('file')
expect(await (await w.ctx.get(token)).get()).toBe('dfoa_test')
expect(JSON.parse(w.io.outBuf())).toMatchObject({ server: w.mock.url, workspace_id: 'ws-1' })
})
it('refuses under an env login', async () => {
const seed = await testContext({ login: false, env: true })
worlds.push(seed)
const w = await testContext({
login: false,
env: true,
argv: ['login', '--server', seed.mock.url],
reuseDirOf: seed,
})
worlds.push(w)
await expect((await w.ctx.get(commands)).run()).rejects.toMatchObject({
code: 'usage_invalid_flag',
message: 'unset DIFY_TOKEN to log in interactively',
})
})
it('checks the verification uri before inviting the operator to open it', async () => {
const seed = await testContext({ login: false })
worlds.push(seed)
const w = await testContext({
login: false,
argv: ['login', '--server', seed.mock.url, '--no-browser', '--no-keyring', '--insecure'],
reuseDirOf: seed,
})
worlds.push(w)
w.mock.setScenario('bad-verification-uri')
await expect((await w.ctx.get(commands)).run()).rejects.toMatchObject({
code: 'unknown',
message: expect.stringContaining('unsupported scheme "ftp"'),
})
expect(w.io.errBuf()).not.toMatch(/open /)
expect(w.io.errBuf()).not.toMatch(/code ABCD-1234/)
})
it('rejects a login response with no usable email and saves nothing', async () => {
const seed = await testContext({ login: false })
worlds.push(seed)
const w = await testContext({
login: false,
argv: ['login', '--server', seed.mock.url, '--no-browser', '--no-keyring', '--insecure'],
reuseDirOf: seed,
})
worlds.push(w)
w.mock.setScenario('no-email')
await expect((await w.ctx.get(commands)).run()).rejects.toMatchObject({
code: 'server_error',
message: 'login response carries no account or subject email',
})
expect(await (await w.ctx.get(session)).current()).toBeNull()
})
it('falls back to the external-SSO subject email when there is no account', async () => {
const seed = await testContext({ login: false })
worlds.push(seed)
const w = await testContext({
login: false,
argv: ['login', '--server', seed.mock.url, '--no-browser', '--no-keyring', '--insecure'],
reuseDirOf: seed,
})
worlds.push(w)
w.mock.setScenario('sso')
expect(await (await w.ctx.get(commands)).run()).toBe(0)
const login = await (await w.ctx.get(session)).current()
expect(login?.email).toBe('sso@dify.ai')
expect(login?.account).toBeNull()
})
it('resume with no pending login reports the saved login', async () => {
const w = await testContext({ login: true, argv: ['login', '--resume'] })
worlds.push(w)
expect(await (await w.ctx.get(commands)).run()).toBe(0)
expect(JSON.parse(w.io.outBuf())).toMatchObject({
server: w.mock.url,
email: 'me@x',
workspace_id: 'ws-1',
})
})
it('resume with no pending login and no saved login is not_logged_in', async () => {
const w = await testContext({ login: false, argv: ['login', '--resume'] })
worlds.push(w)
await expect((await w.ctx.get(commands)).run()).rejects.toMatchObject({
code: 'not_logged_in',
message: `not logged in: no login saved in ${w.dir}; DIFY_CONFIG_DIR picks this folder`,
})
})
it('resume with no pending login and the token gone is not_logged_in', async () => {
const w = await testContext({ login: true, argv: ['login', '--resume'] })
worlds.push(w)
const fresh = new Context()
const login = await (await fresh.get(session)).require()
await (await fresh.get(token)).remove(login)
await expect((await w.ctx.get(commands)).run()).rejects.toMatchObject({ code: 'not_logged_in' })
})
it('resume under an env login reports the env login', async () => {
const w = await testContext({ login: false, env: true, argv: ['login', '--resume'] })
worlds.push(w)
expect(await (await w.ctx.get(commands)).run()).toBe(0)
expect(JSON.parse(w.io.outBuf())).toMatchObject({ server: w.mock.url, email: 'env' })
})
it('a new login drops a pending --no-wait login', async () => {
const seed = await testContext({ login: false })
worlds.push(seed)
const pendingFile = join(seed.dir, PENDING_FILE_NAME)
writeFileSync(
pendingFile,
`server: ${seed.mock.url}\ninsecure: true\nno_keyring: true\ndevice_code: stale\n`,
)
const w = await testContext({
login: false,
argv: ['login', '--server', seed.mock.url, '--no-browser', '--no-keyring', '--insecure'],
reuseDirOf: seed,
})
worlds.push(w)
expect(await (await w.ctx.get(commands)).run()).toBe(0)
expect(existsSync(pendingFile)).toBe(false)
})
it.each([[[]], [['--server', ' ']]])(
'refuses to start without a server, keeping a pending login',
async (flags) => {
const seed = await testContext({ login: false })
worlds.push(seed)
const pendingPath = join(seed.dir, PENDING_FILE_NAME)
writeFileSync(
pendingPath,
`server: ${seed.mock.url}\ninsecure: true\nno_keyring: true\ndevice_code: kept\n`,
)
const w = await testContext({
login: false,
argv: ['login', '--no-wait', ...flags],
reuseDirOf: seed,
})
worlds.push(w)
await expect((await w.ctx.get(commands)).run()).rejects.toMatchObject({
code: 'usage_missing_arg',
hint: 'ask the user which server; Dify Cloud is https://cloud.dify.ai',
})
expect(existsSync(pendingPath)).toBe(true)
},
)
it('keeps a pending login when the new --server is rejected', async () => {
const seed = await testContext({ login: false })
worlds.push(seed)
const pendingPath = join(seed.dir, PENDING_FILE_NAME)
writeFileSync(
pendingPath,
`server: ${seed.mock.url}\ninsecure: true\nno_keyring: true\ndevice_code: kept\n`,
)
const w = await testContext({
login: false,
argv: ['login', '--server', 'http://plain.example.com', '--no-wait'],
reuseDirOf: seed,
})
worlds.push(w)
await expect((await w.ctx.get(commands)).run()).rejects.toMatchObject({
code: 'usage_invalid_flag',
})
expect(existsSync(pendingPath)).toBe(true)
})
it('resume under an env login refuses a pending login before polling', async () => {
const seed = await testContext({ login: false, env: true })
worlds.push(seed)
const pendingPath = join(seed.dir, PENDING_FILE_NAME)
writeFileSync(
pendingPath,
`server: ${seed.mock.url}\ninsecure: true\nno_keyring: true\ndevice_code: kept\n`,
)
const w = await testContext({
login: false,
env: true,
argv: ['login', '--resume'],
reuseDirOf: seed,
})
worlds.push(w)
await expect((await w.ctx.get(commands)).run()).rejects.toMatchObject({
code: 'usage_invalid_flag',
message: 'unset DIFY_TOKEN to log in interactively',
})
expect(existsSync(pendingPath)).toBe(true)
})
it.each(['happy', 'denied', 'expired'] as const)(
'resume (%s) leaves a pending login another process saved meanwhile',
async (scenario) => {
const seed = await testContext({ login: false })
worlds.push(seed)
const pendingPath = join(seed.dir, PENDING_FILE_NAME)
const pendingFor = (code: string) =>
`server: ${seed.mock.url}\ninsecure: true\nno_keyring: true\ndevice_code: ${code}\n`
writeFileSync(pendingPath, pendingFor('dc-1'))
seed.mock.setScenario(scenario)
seed.mock.onDeviceTokenPoll(() => writeFileSync(pendingPath, pendingFor('dc-2')))
const w = await testContext({ login: false, argv: ['login', '--resume'], reuseDirOf: seed })
worlds.push(w)
await (await w.ctx.get(commands)).run().catch(() => undefined)
expect(readFileSync(pendingPath, 'utf8')).toContain('device_code: dc-2')
},
)
it.each(['happy', 'denied', 'expired'] as const)(
'resume (%s) clears its own pending login',
async (scenario) => {
const seed = await testContext({ login: false })
worlds.push(seed)
const pendingPath = join(seed.dir, PENDING_FILE_NAME)
writeFileSync(
pendingPath,
`server: ${seed.mock.url}\ninsecure: true\nno_keyring: true\ndevice_code: dc-1\n`,
)
seed.mock.setScenario(scenario)
const w = await testContext({ login: false, argv: ['login', '--resume'], reuseDirOf: seed })
worlds.push(w)
await (await w.ctx.get(commands)).run().catch(() => undefined)
expect(existsSync(pendingPath)).toBe(false)
},
)
@@ -0,0 +1,204 @@
import type { PollSuccess } from '@/auth/device-api'
import type { Pending, PendingLoginStore } from '@/auth/pending-login'
import type { CommandContext } from '@/plugins/base'
import type { Login as SavedLogin } from '@/plugins/session'
import { hostname } from 'node:os'
import { z } from 'zod'
import { deviceApi } from '@/auth/device-api'
import { awaitAuthorization, pollAuthorization, realClock } from '@/auth/device-flow'
import { assertNotEnvLogin, revokeAndClearSession } from '@/auth/logout'
import { pendingLoginStore } from '@/auth/pending-login'
import { BaseError } from '@/errors/base'
import { ErrorCode } from '@/errors/codes'
import { Command } from '@/plugins/commands/command'
import { io } from '@/plugins/io'
import { session } from '@/plugins/session'
import { token, TOKENS_FILE_NAME } from '@/plugins/token'
import { decideOpen, OpenDecision, openUrl, realEnv } from '@/util/browser'
import { resolveHost, validateVerificationURI } from '@/util/host'
const INPUT = z.object({
server: z
.string()
.trim()
.optional()
.describe('Dify server base URL. Required to start a login; there is no default'),
no_browser: z
.boolean()
.default(false)
.describe('Do not open a browser; print the URL and code for the user'),
no_keyring: z
.boolean()
.default(false)
.describe(
`Keep the token in ${TOKENS_FILE_NAME} under the config dir instead of the OS keyring. Use in a sandbox, with DIFY_CONFIG_DIR on persistent storage`,
),
insecure: z
.boolean()
.default(false)
.describe('Skip TLS verification and allow http:// (local dev only)'),
no_wait: z
.boolean()
.default(false)
.describe('Print the URL and code, save the pending login, and exit without waiting'),
resume: z
.boolean()
.default(false)
.describe(
'Check a login started with --no-wait once. Prints status pending until the user approves. With no pending login, prints the saved login, or fails with not_logged_in',
),
})
const PENDING_STATUS = 'pending'
const FINAL_POLL_ERRORS: readonly string[] = [ErrorCode.AuthExpired, ErrorCode.AccessDenied]
const ENV_LOGIN_MESSAGE = 'unset DIFY_TOKEN to log in interactively'
const NO_EMAIL_MESSAGE = 'login response carries no account or subject email'
const NO_SERVER_MESSAGE = 'pass --server <url>: the Dify server to log in to'
const NO_SERVER_HINT = 'ask the user which server; Dify Cloud is https://cloud.dify.ai'
// A present-but-empty email is the same as absent: neither account.email nor
// subject_email is meaningful until it has a value.
function meaningfulEmail(value: string | undefined): string | undefined {
return value === undefined || value === '' ? undefined : value
}
export default class Login extends Command<typeof INPUT> {
static override summary =
'Log in via the OAuth device flow. Agents: use --no-wait, then --resume after the user approves'
static override effect = 'write' as const
static override input = INPUT
static override examples = [
{
title: 'Agent: start without waiting, give the user the url and code, then end the turn',
input: { server: 'https://dify.example.com', no_browser: true, no_wait: true },
},
{
title: 'Agent in a sandbox: add --no-keyring and point DIFY_CONFIG_DIR at persistent storage',
input: {
server: 'https://dify.example.com',
no_browser: true,
no_wait: true,
no_keyring: true,
},
},
{
title: 'Finish a --no-wait login once the user says they approved',
input: { resume: true },
},
]
async run(input: z.infer<typeof INPUT>, ctx: CommandContext) {
const pendingLogin = await pendingLoginStore(ctx)
if (input.resume) return resume(ctx, pendingLogin)
const sessionService = await ctx.get(session)
assertNotEnvLogin(sessionService.fromEnv, ENV_LOGIN_MESSAGE)
if (input.server === undefined || input.server === '')
throw new BaseError({
code: ErrorCode.UsageMissingArg,
message: NO_SERVER_MESSAGE,
hint: NO_SERVER_HINT,
})
const server = resolveHost({ raw: input.server, insecure: input.insecure })
const streams = await ctx.get(io)
const current = await sessionService.current()
if (current !== null) {
await revokeAndClearSession(ctx, current)
streams.notice(`logged out ${current.email} from ${current.server}`)
}
const api = deviceApi(server, { insecure: input.insecure })
const code = await api.requestCode({ device_label: hostname() })
// Checked before it is printed: a URI difyctl would refuse to open is one the
// operator should not be invited to paste either.
validateVerificationURI(code.verification_uri, input.insecure)
streams.notice(`open ${code.verification_uri}`)
streams.notice(`code ${code.user_code}`)
const decision = decideOpen(realEnv(), input.no_browser)
if (decision === OpenDecision.Auto) await openUrl(code.verification_uri)
const pending: Pending = {
server,
insecure: input.insecure,
no_keyring: input.no_keyring,
device_code: code.device_code,
}
if (input.no_wait) {
await pendingLogin.save(pending)
return {
status: PENDING_STATUS,
verification_uri: code.verification_uri,
user_code: code.user_code,
expires_in: code.expires_in,
}
}
await pendingLogin.clear()
const success = await awaitAuthorization(api, code, { clock: realClock() })
return finish(ctx, pending, success)
}
}
function loginReport(login: SavedLogin) {
return {
server: login.server,
email: login.email,
account: login.account,
workspace_id: login.workspaceId,
}
}
// `get` throws not_logged_in when the saved login's token is gone from the store.
async function assertTokenSaved(ctx: CommandContext): Promise<void> {
await (await ctx.get(token)).get()
}
async function resume(ctx: CommandContext, pendingLogin: PendingLoginStore) {
const sessionService = await ctx.get(session)
const pending = await pendingLogin.read()
if (pending === null) {
const current = await sessionService.require()
await assertTokenSaved(ctx)
return loginReport(current)
}
assertNotEnvLogin(sessionService.fromEnv, ENV_LOGIN_MESSAGE)
const api = deviceApi(pending.server, { insecure: pending.insecure })
let success: PollSuccess | undefined
try {
success = await pollAuthorization(api, pending.device_code, { clock: realClock() })
} catch (err) {
if (err instanceof BaseError && FINAL_POLL_ERRORS.includes(err.code))
await pendingLogin.clearIf(pending.device_code)
throw err
}
if (success === undefined) return { status: PENDING_STATUS }
const result = await finish(ctx, pending, success)
await pendingLogin.clearIf(pending.device_code)
return result
}
async function finish(ctx: CommandContext, pending: Pending, success: PollSuccess) {
const sessionService = await ctx.get(session)
const tokenService = await ctx.get(token)
const tokenStorage = await tokenService.detect({ skipKeyring: pending.no_keyring })
const email = meaningfulEmail(success.account?.email) ?? meaningfulEmail(success.subject_email)
if (email === undefined) {
throw new BaseError({ code: ErrorCode.ServerError, message: NO_EMAIL_MESSAGE })
}
const login: SavedLogin = {
server: pending.server,
email,
account: success.account ?? null,
workspaceId: success.default_workspace_id ?? null,
tokenStorage,
insecure: pending.insecure,
}
await sessionService.save(login)
await tokenService.write(login, success.token)
return loginReport(login)
}
@@ -0,0 +1,86 @@
import type { TestWorld } from '@test/fixtures/kernel'
import { existsSync, readdirSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
import { testContext } from '@test/fixtures/kernel'
import { afterEach, expect, it } from 'vite-plus/test'
import { PENDING_FILE_NAME } from '@/auth/pending-login'
import { Context } from '@/kernel/context'
import { commands } from '@/plugins/commands'
import { session } from '@/plugins/session'
import { token } from '@/plugins/token'
const worlds: TestWorld[] = []
afterEach(async () => {
for (const w of worlds.splice(0)) await w.stop()
})
function catalogFiles(dir: string): string[] {
const catalogDir = join(dir, 'catalog')
return existsSync(catalogDir) ? readdirSync(catalogDir) : []
}
it('revokes the session on the server and clears local state', async () => {
const w = await testContext({ login: true, argv: ['logout'] })
worlds.push(w)
expect(await (await w.ctx.get(commands)).run()).toBe(0)
expect(JSON.parse(w.io.outBuf())).toEqual({ logged_out: true, server: w.mock.url })
expect(w.io.errBuf()).toBe('')
expect(await (await w.ctx.get(session)).current()).toBeNull()
expect(catalogFiles(w.dir)).toEqual([])
await expect((await new Context().get(token)).get()).rejects.toMatchObject({
code: 'not_logged_in',
})
})
it('drops a pending --no-wait login', async () => {
const w = await testContext({ login: true, argv: ['logout'] })
worlds.push(w)
const pendingFile = join(w.dir, PENDING_FILE_NAME)
writeFileSync(pendingFile, 'device_code: stale\n')
expect(await (await w.ctx.get(commands)).run()).toBe(0)
expect(existsSync(pendingFile)).toBe(false)
})
it('drops a pending --no-wait login when nobody is logged in', async () => {
const w = await testContext({ login: false, argv: ['logout'] })
worlds.push(w)
const pendingFile = join(w.dir, PENDING_FILE_NAME)
writeFileSync(pendingFile, 'device_code: stale\n')
await expect((await w.ctx.get(commands)).run()).rejects.toMatchObject({ code: 'not_logged_in' })
expect(existsSync(pendingFile)).toBe(false)
})
it('still clears local state and reports a failed server revoke', async () => {
const w = await testContext({ login: true, argv: ['logout'] })
worlds.push(w)
w.mock.setScenario('server-5xx')
expect(await (await w.ctx.get(commands)).run()).toBe(0)
expect(w.io.errBuf()).toMatch(/^server revoke failed:/)
expect(await (await w.ctx.get(session)).current()).toBeNull()
expect(catalogFiles(w.dir)).toEqual([])
await expect((await new Context().get(token)).get()).rejects.toMatchObject({
code: 'not_logged_in',
})
})
it('refuses under an env login', async () => {
const w = await testContext({ login: false, env: true, argv: ['logout'] })
worlds.push(w)
await expect((await w.ctx.get(commands)).run()).rejects.toMatchObject({
code: 'usage_invalid_flag',
message: 'nothing to log out: the login comes from DIFY_TOKEN',
})
})
it('refuses under an env login without dropping a pending interactive login', async () => {
const w = await testContext({ login: false, env: true, argv: ['logout'] })
worlds.push(w)
const pendingFile = join(w.dir, PENDING_FILE_NAME)
writeFileSync(pendingFile, 'device_code: dc-1\n')
await expect((await w.ctx.get(commands)).run()).rejects.toMatchObject({
code: 'usage_invalid_flag',
})
expect(existsSync(pendingFile)).toBe(true)
})
@@ -0,0 +1,27 @@
import type { CommandContext } from '@/plugins/base'
import { z } from 'zod'
import { assertNotEnvLogin, revokeAndClearSession } from '@/auth/logout'
import { pendingLoginStore } from '@/auth/pending-login'
import { Command } from '@/plugins/commands/command'
import { session } from '@/plugins/session'
const INPUT = z.object({})
const ENV_LOGOUT_MESSAGE = 'nothing to log out: the login comes from DIFY_TOKEN'
export default class Logout extends Command<typeof INPUT> {
static override summary = 'Log out of the current Dify session'
static override effect = 'write' as const
static override input = INPUT
async run(_input: z.infer<typeof INPUT>, ctx: CommandContext) {
const sessionService = await ctx.get(session)
// Refuse before touching anything: an env login must leave a pending interactive login alone.
assertNotEnvLogin(sessionService.fromEnv, ENV_LOGOUT_MESSAGE)
await (await pendingLoginStore(ctx)).clear()
const login = await sessionService.require()
await revokeAndClearSession(ctx, login)
return { logged_out: true, server: login.server }
}
}
@@ -0,0 +1,25 @@
import type { TestWorld } from '@test/fixtures/kernel'
import { createHash } from 'node:crypto'
import { readFileSync } from 'node:fs'
import { join } from 'node:path'
import { testContext } from '@test/fixtures/kernel'
import { afterEach, expect, it } from 'vite-plus/test'
import { commands } from '@/plugins/commands'
const FIXTURE = readFileSync(join(__dirname, '../../../../test/fixtures/catalog.json'))
const FINGERPRINT = createHash('sha256').update(FIXTURE).digest('hex')
const worlds: TestWorld[] = []
afterEach(async () => {
for (const w of worlds.splice(0)) await w.stop()
})
it('writes the catalog file and reports the op count and fingerprint', async () => {
const w = await testContext({ login: true, argv: ['refresh', 'cache'] })
worlds.push(w)
expect(await (await w.ctx.get(commands)).run()).toBe(0)
const body = JSON.parse(w.io.outBuf()) as { ops: number; fingerprint: string; path: string }
expect(body.fingerprint).toBe(FINGERPRINT)
expect(body.ops).toBeGreaterThan(20)
expect(readFileSync(body.path)).toEqual(FIXTURE)
})
+25
View File
@@ -0,0 +1,25 @@
import type { CommandContext } from '@/plugins/base'
import { z } from 'zod'
import { catalog } from '@/plugins/catalog'
import { Command } from '@/plugins/commands/command'
import { http } from '@/plugins/http'
const INPUT = z.object({})
export default class CacheRefresh extends Command<typeof INPUT> {
static override summary = 'Refetch the server catalog and replace the local cache'
static override effect = 'write' as const
static override input = INPUT
async run(_input: z.infer<typeof INPUT>, ctx: CommandContext) {
const httpService = await ctx.get(http)
const catalogService = await ctx.get(catalog)
await catalogService.replace(await httpService.fetchCatalog())
return {
ops: Object.keys(catalogService.ops()).length,
fingerprint: catalogService.fingerprint,
path: catalogService.path,
}
}
}
@@ -0,0 +1,25 @@
import type { TestWorld } from '@test/fixtures/kernel'
import { testContext } from '@test/fixtures/kernel'
import { afterEach, expect, it } from 'vite-plus/test'
import { commands } from '@/plugins/commands'
import { config } from '@/plugins/config'
const worlds: TestWorld[] = []
afterEach(async () => {
for (const w of worlds.splice(0)) await w.stop()
})
it('writes a value that the config service can read back', async () => {
const w = await testContext({ login: false, argv: ['set', 'config', 'http.timeout', '5000'] })
worlds.push(w)
expect(await (await w.ctx.get(commands)).run()).toBe(0)
expect(await (await w.ctx.get(config)).get('http.timeout')).toBe(5000)
})
it('rejects an unknown key with exit 2', async () => {
const w = await testContext({ login: false, argv: ['set', 'config', 'nope', '1'] })
worlds.push(w)
await expect((await w.ctx.get(commands)).run()).rejects.toMatchObject({
code: 'config_invalid_key',
})
})
@@ -0,0 +1,19 @@
import type { CommandContext } from '@/plugins/base'
import { z } from 'zod'
import { Command } from '@/plugins/commands/command'
import { config } from '@/plugins/config'
const INPUT = z.object({ key: z.string(), value: z.string() })
export default class ConfigSet extends Command<typeof INPUT> {
static override summary = 'Set a local config value'
static override effect = 'write' as const
static override input = INPUT
static override positional = ['key', 'value'] as const
async run(input: z.infer<typeof INPUT>, ctx: CommandContext) {
const configService = await ctx.get(config)
await configService.set(input.key, input.value)
return undefined
}
}
+55
View File
@@ -0,0 +1,55 @@
// @generated by scripts/generate-command-tree.ts — DO NOT EDIT.
// Regenerate via `pnpm tree:gen`. Drift gated by `pnpm tree:check` in CI.
import type { CommandTree } from '@/plugins/commands/registry'
import DeleteCache from '@/commands/delete/cache/index'
import GetConfig from '@/commands/get/config/index'
import InstallSkills from '@/commands/install/skills/index'
import Login from '@/commands/login/index'
import Logout from '@/commands/logout/index'
import RefreshCache from '@/commands/refresh/cache/index'
import SetConfig from '@/commands/set/config/index'
import UnsetConfig from '@/commands/unset/config/index'
import UseWorkspace from '@/commands/use/workspace/index'
import Version from '@/commands/version/index'
export const commandTree: CommandTree = {
delete: {
subcommands: {
cache: { command: DeleteCache, subcommands: {} },
},
},
get: {
subcommands: {
config: { command: GetConfig, subcommands: {} },
},
},
install: {
subcommands: {
skills: { command: InstallSkills, subcommands: {} },
},
},
login: { command: Login, subcommands: {} },
logout: { command: Logout, subcommands: {} },
refresh: {
subcommands: {
cache: { command: RefreshCache, subcommands: {} },
},
},
set: {
subcommands: {
config: { command: SetConfig, subcommands: {} },
},
},
unset: {
subcommands: {
config: { command: UnsetConfig, subcommands: {} },
},
},
use: {
subcommands: {
workspace: { command: UseWorkspace, subcommands: {} },
},
},
version: { command: Version, subcommands: {} },
}
+1
View File
@@ -0,0 +1 @@
export { commandTree } from './tree.generated'
@@ -0,0 +1,26 @@
import type { TestWorld } from '@test/fixtures/kernel'
import { testContext } from '@test/fixtures/kernel'
import { afterEach, expect, it } from 'vite-plus/test'
import { commands } from '@/plugins/commands'
import { config } from '@/plugins/config'
const worlds: TestWorld[] = []
afterEach(async () => {
for (const w of worlds.splice(0)) await w.stop()
})
it('removes a value, restoring its default', async () => {
const w = await testContext({ login: false, argv: ['unset', 'config', 'http.timeout'] })
worlds.push(w)
await (await w.ctx.get(config)).set('http.timeout', '5000')
expect(await (await w.ctx.get(commands)).run()).toBe(0)
expect(await (await w.ctx.get(config)).get('http.timeout')).toBe(30_000)
})
it('rejects an unknown key with exit 2', async () => {
const w = await testContext({ login: false, argv: ['unset', 'config', 'nope'] })
worlds.push(w)
await expect((await w.ctx.get(commands)).run()).rejects.toMatchObject({
code: 'config_invalid_key',
})
})
@@ -0,0 +1,19 @@
import type { CommandContext } from '@/plugins/base'
import { z } from 'zod'
import { Command } from '@/plugins/commands/command'
import { config } from '@/plugins/config'
const INPUT = z.object({ key: z.string() })
export default class ConfigUnset extends Command<typeof INPUT> {
static override summary = 'Remove a local config value, restoring its default'
static override effect = 'write' as const
static override input = INPUT
static override positional = ['key'] as const
async run(input: z.infer<typeof INPUT>, ctx: CommandContext) {
const configService = await ctx.get(config)
await configService.unset(input.key)
return undefined
}
}
@@ -0,0 +1,69 @@
import type { TestWorld } from '@test/fixtures/kernel'
import type { BaseError } from '@/errors/base'
import { testContext } from '@test/fixtures/kernel'
import { afterEach, expect, it } from 'vite-plus/test'
import { ExitCode } from '@/errors/codes'
import { commands } from '@/plugins/commands'
import { ENV } from '@/plugins/env'
import { session } from '@/plugins/session'
const worlds: TestWorld[] = []
afterEach(async () => {
for (const w of worlds.splice(0)) await w.stop()
})
it('pins a workspace the account belongs to and names it', async () => {
const w = await testContext({ login: true, argv: ['use', 'workspace', 'ws-2'] })
worlds.push(w)
expect(await (await w.ctx.get(commands)).run()).toBe(0)
expect(JSON.parse(w.io.outBuf())).toEqual({ workspace_id: 'ws-2', name: 'Other' })
expect(await (await w.ctx.get(session)).workspaceId()).toBe('ws-2')
})
it('describe workspace with no id shows the pinned workspace', async () => {
const w = await testContext({ login: true, argv: ['describe', 'workspace'] })
worlds.push(w)
expect(await (await w.ctx.get(commands)).run()).toBe(0)
expect(JSON.parse(w.io.outBuf())).toMatchObject({ id: 'ws-1', name: 'Default' })
})
it('refuses a workspace the account does not belong to and keeps the old pin', async () => {
const w = await testContext({ login: true, argv: ['use', 'workspace', 'ws-9'] })
worlds.push(w)
const err = await (await w.ctx.get(commands)).run().catch((e: unknown) => e)
expect(err).toMatchObject({ message: 'workspace not found' })
expect((err as BaseError).exit()).toBe(ExitCode.Generic)
expect(await (await w.ctx.get(session)).workspaceId()).toBe('ws-1')
})
it('refuses under an env login and without a login', async () => {
const a = await testContext({ login: false, env: true, argv: ['use', 'workspace', 'ws-9'] })
worlds.push(a)
await expect((await a.ctx.get(commands)).run()).rejects.toMatchObject({
code: 'usage_invalid_flag',
message: 'the login comes from DIFY_TOKEN; set DIFY_WORKSPACE_ID instead',
})
const b = await testContext({ login: false, argv: ['use', 'workspace', 'ws-9'] })
worlds.push(b)
await expect((await b.ctx.get(commands)).run()).rejects.toMatchObject({ code: 'not_logged_in' })
})
it('refuses an empty workspace id, exit 2, and changes nothing', async () => {
const w = await testContext({ login: true, argv: ['use', 'workspace', ''] })
worlds.push(w)
await expect((await w.ctx.get(commands)).run()).rejects.toMatchObject({
code: 'input_invalid',
details: [expect.objectContaining({ loc: ['workspace_id'] })],
})
expect(await (await w.ctx.get(session)).workspaceId()).toBe('ws-1')
})
it('refuses when DIFY_WORKSPACE_ID overrides the pin', async () => {
const w = await testContext({ login: true, argv: ['use', 'workspace', 'ws-9'] })
worlds.push(w)
process.env[ENV.WorkspaceId] = 'ws-9'
await expect((await w.ctx.get(commands)).run()).rejects.toMatchObject({
code: 'usage_invalid_flag',
message: 'DIFY_WORKSPACE_ID is set; unset it to pin locally',
})
})
@@ -0,0 +1,56 @@
import type { CommandContext } from '@/plugins/base'
import { z } from 'zod'
import { assertNotEnvLogin } from '@/auth/logout'
import { LOCAL_FILES } from '@/call/files'
import { parseJsonBody } from '@/call/json-body'
import { buildRequest } from '@/call/request'
import { BaseError } from '@/errors/base'
import { ErrorCode } from '@/errors/codes'
import { Command } from '@/plugins/commands/command'
import { env } from '@/plugins/env'
import { http } from '@/plugins/http'
import { session } from '@/plugins/session'
const INPUT = z.object({ workspace_id: z.string().min(1) })
const WORKSPACE = z.object({ id: z.string(), name: z.string() })
const WORKSPACE_DESCRIBE_OP = 'describe.workspace'
const ENV_WORKSPACE_ID_MESSAGE = 'DIFY_WORKSPACE_ID is set; unset it to pin locally'
const ENV_LOGIN_MESSAGE = 'the login comes from DIFY_TOKEN; set DIFY_WORKSPACE_ID instead'
const MALFORMED_WORKSPACE_MESSAGE = 'describe workspace response has no id and name'
export default class WorkspaceUse extends Command<typeof INPUT> {
static override summary =
'Pin this device to a workspace; the web console keeps its own current workspace'
static override effect = 'write' as const
static override input = INPUT
static override positional = ['workspace_id'] as const
async run(input: z.infer<typeof INPUT>, ctx: CommandContext) {
const envService = await ctx.get(env)
if (envService.workspaceId !== undefined) {
throw new BaseError({ code: ErrorCode.UsageInvalidFlag, message: ENV_WORKSPACE_ID_MESSAGE })
}
const sessionService = await ctx.get(session)
const login = await sessionService.require()
assertNotEnvLogin(sessionService.fromEnv, ENV_LOGIN_MESSAGE)
// Check membership first so a mistyped id is never pinned.
const httpService = await ctx.get(http)
const res = await httpService.request(async (cat) =>
buildRequest(
cat.opOrThrow(WORKSPACE_DESCRIBE_OP),
{ workspace_id: input.workspace_id },
LOCAL_FILES,
),
)
const workspace = WORKSPACE.safeParse(await parseJsonBody(res))
if (!workspace.success)
throw new BaseError({ code: ErrorCode.ServerError, message: MALFORMED_WORKSPACE_MESSAGE })
await sessionService.save({ ...login, workspaceId: workspace.data.id })
return { workspace_id: workspace.data.id, name: workspace.data.name }
}
}
@@ -0,0 +1,27 @@
import type { TestWorld } from '@test/fixtures/kernel'
import { testContext } from '@test/fixtures/kernel'
import { afterEach, expect, it } from 'vite-plus/test'
import { commands } from '@/plugins/commands'
const worlds: TestWorld[] = []
afterEach(async () => {
for (const w of worlds.splice(0)) await w.stop()
})
it('prints the client version without a login and adds the server with one', async () => {
const a = await testContext({ login: false, argv: ['version'] })
worlds.push(a)
expect(await (await a.ctx.get(commands)).run()).toBe(0)
expect(JSON.parse(a.io.outBuf())).toEqual({
client: {
version: '0.0.0-test',
commit: '0000000',
channel: 'dev',
build_date: '1970-01-01T00:00:00.000Z',
},
})
const b = await testContext({ login: true, argv: ['version'] })
worlds.push(b)
await (await b.ctx.get(commands)).run()
expect(JSON.parse(b.io.outBuf()).server).toEqual({ version: '1.6.4', edition: 'CLOUD' })
})
@@ -0,0 +1,46 @@
import type { CommandContext } from '@/plugins/base'
import { z } from 'zod'
import { parseJsonBody } from '@/call/json-body'
import { errorMessage } from '@/errors/message'
import { Command } from '@/plugins/commands/command'
import { http } from '@/plugins/http'
import { io } from '@/plugins/io'
import { session } from '@/plugins/session'
import { versionInfo } from '@/version/info'
const INPUT = z.object({})
const SERVER_VERSION_PATH = '/openapi/v1/_version'
const SERVER_VERSION_UNAVAILABLE_PREFIX = 'server version unavailable: '
type ServerVersion = { version: string; edition: string }
export default class Version extends Command<typeof INPUT> {
static override summary = 'Print the client and server versions'
static override input = INPUT
async run(_input: z.infer<typeof INPUT>, ctx: CommandContext) {
const client = {
version: versionInfo.version,
commit: versionInfo.commit,
channel: versionInfo.channel,
build_date: versionInfo.buildDate,
}
const login = await (await ctx.get(session)).current()
if (login === null) return { client }
const streams = await ctx.get(io)
const httpService = await ctx.get(http)
try {
const res = await httpService.request(() => ({
method: 'GET',
path: SERVER_VERSION_PATH,
auth: false,
}))
const body = (await parseJsonBody(res)) as ServerVersion
return { client, server: { version: body.version, edition: body.edition } }
} catch (err) {
streams.notice(`${SERVER_VERSION_UNAVAILABLE_PREFIX}${errorMessage(err)}`)
return { client, server: null }
}
}
}
@@ -0,0 +1,26 @@
import type { Describable, SearchDoc } from './search'
import { expect, it } from 'vite-plus/test'
import { search, searchDoc } from './search'
function doc(id: string, source: Partial<Describable>, deprecated = false): SearchDoc {
return searchDoc(id, { summary: '', input: {}, examples: [], ...source }, deprecated)
}
const DOCS = [
doc('run.console_app.chat', { summary: 'Run a chat or agent app' }),
doc('run.console_app.workflow', { summary: 'Run a workflow app' }),
doc('get.console_app', { input: { properties: { page: { description: 'Page number' } } } }),
doc('console_app.run', { summary: 'Deprecated: use the per-mode run' }, true),
]
const ids = (query: string) => search(DOCS, query, { limit: 20 }).hits.map((hit) => hit.id)
it('ranks id tokens first, reaches schema text, takes compounds and typos, keeps deprecated last', () => {
expect(ids('workflow')[0]).toBe('run.console_app.workflow')
expect(ids('agents nonsense')).toEqual(['run.console_app.chat'])
expect(ids('page')).toEqual(['get.console_app'])
expect(ids('chatbot')[0]).toBe('run.console_app.chat')
expect(ids('worflow')[0]).toBe('run.console_app.workflow')
expect(ids('running').at(-1)).toBe('console_app.run')
expect(search(DOCS, 'app', { limit: 1 })).toMatchObject({ total: 4 })
expect(ids('the zebra')).toEqual([])
})
+205
View File
@@ -0,0 +1,205 @@
import type { Example, JsonSchema } from '@/plugins/catalog'
import { editDistance } from '@/util/edit-distance'
import { isRecord } from '@/util/is-record'
export const FIELD = {
Id: 'id',
Summary: 'summary',
Example: 'example',
Input: 'input',
} as const
export type Field = (typeof FIELD)[keyof typeof FIELD]
const WEIGHT: Readonly<Record<Field, number>> = {
[FIELD.Id]: 5,
[FIELD.Summary]: 3,
[FIELD.Example]: 2,
[FIELD.Input]: 1,
}
const FIELDS = Object.values(FIELD)
export type Describable = Readonly<{
summary: string
input: JsonSchema
examples: readonly Example[]
}>
export type SearchDoc = Readonly<{
id: string
deprecated: boolean
fields: Readonly<Record<Field, readonly string[]>>
}>
export type SearchHit = Readonly<{ id: string; score: number }>
export type SearchResult = Readonly<{ hits: readonly SearchHit[]; total: number }>
const TOKEN_BREAK = /[^a-z0-9]+/
const STOPWORDS: ReadonlySet<string> = new Set([
'a',
'an',
'and',
'as',
'at',
'be',
'by',
'for',
'from',
'in',
'is',
'it',
'its',
'of',
'on',
'or',
'the',
'this',
'to',
'with',
])
const SCHEMA_KEYS_WITH_TEXT = ['description', 'title'] as const
const SCHEMA_DEPTH_LIMIT = 4
const RUNG_EXACT = 1
const RUNG_TERM_PREFIX = 0.6
const RUNG_TOKEN_PREFIX = 0.5
const RUNG_TYPO = 0.4
const RUNG_NONE = 0
const TERM_PREFIX_MIN = 3
const TOKEN_PREFIX_MIN = 4
const TYPO_MIN = 5
const TYPO_DISTANCE = 1
const K1 = 1.2
const B = 0.75
function stem(token: string): string {
if (token.length > 4 && token.endsWith('ies')) return `${token.slice(0, -3)}y`
if (token.length > 5 && token.endsWith('ing')) return undouble(token.slice(0, -3))
if (token.length > 4 && token.endsWith('ed')) return undouble(token.slice(0, -2))
if (token.length > 3 && token.endsWith('s') && !token.endsWith('ss')) return token.slice(0, -1)
return token
}
function undouble(token: string): string {
const last = token.at(-1)
if (last === undefined || last !== token.at(-2) || 'lsz'.includes(last)) return token
return token.slice(0, -1)
}
export function tokenize(text: string): string[] {
return text
.toLowerCase()
.split(TOKEN_BREAK)
.filter((token) => token !== '' && !STOPWORDS.has(token))
.map(stem)
}
function schemaText(schema: unknown, depth: number, out: string[]): void {
if (!isRecord(schema) || depth > SCHEMA_DEPTH_LIMIT) return
for (const key of SCHEMA_KEYS_WITH_TEXT) {
const value = schema[key]
if (typeof value === 'string') out.push(value)
}
const properties = schema.properties
if (isRecord(properties)) {
for (const [name, child] of Object.entries(properties)) {
out.push(name)
schemaText(child, depth + 1, out)
}
}
schemaText(schema.items, depth + 1, out)
}
export function searchDoc(id: string, source: Describable, deprecated: boolean): SearchDoc {
const input: string[] = []
schemaText(source.input, 0, input)
return {
id,
deprecated,
fields: {
[FIELD.Id]: tokenize(id),
[FIELD.Summary]: tokenize(source.summary),
[FIELD.Example]: tokenize(source.examples.map((example) => example.title).join(' ')),
[FIELD.Input]: tokenize(input.join(' ')),
},
}
}
function rung(term: string, token: string): number {
if (term === token) return RUNG_EXACT
if (term.length >= TERM_PREFIX_MIN && token.startsWith(term)) return RUNG_TERM_PREFIX
if (token.length >= TOKEN_PREFIX_MIN && term.startsWith(token)) return RUNG_TOKEN_PREFIX
if (term.length >= TYPO_MIN && editDistance(term, token) <= TYPO_DISTANCE) return RUNG_TYPO
return RUNG_NONE
}
function frequency(term: string, tokens: readonly string[]): number {
let total = 0
for (const token of tokens) total += rung(term, token)
return total
}
function averageLengths(docs: readonly SearchDoc[]): Record<Field, number> {
const out = {} as Record<Field, number>
for (const field of FIELDS) {
const sum = docs.reduce((acc, doc) => acc + doc.fields[field].length, 0)
out[field] = docs.length === 0 ? 0 : sum / docs.length
}
return out
}
function saturate(tf: number, length: number, average: number): number {
const norm = average === 0 ? 1 : 1 - B + (B * length) / average
return (tf * (K1 + 1)) / (tf + K1 * norm)
}
function idf(matching: number, total: number): number {
return Math.log(1 + (total - matching + 0.5) / (matching + 0.5))
}
function compare(a: SearchDoc & SearchHit, b: SearchDoc & SearchHit): number {
if (a.deprecated !== b.deprecated) return a.deprecated ? 1 : -1
if (a.score !== b.score) return b.score - a.score
return a.id < b.id ? -1 : 1
}
export function search(
docs: readonly SearchDoc[],
query: string,
opts: Readonly<{ limit: number }>,
): SearchResult {
const terms = [...new Set(tokenize(query))]
const average = averageLengths(docs)
const scores = new Map<string, number>(docs.map((doc) => [doc.id, 0]))
for (const term of terms) {
const perDoc = docs.map((doc) => {
const tf = {} as Record<Field, number>
for (const field of FIELDS) tf[field] = frequency(term, doc.fields[field])
return tf
})
const matching = perDoc.filter((tf) => FIELDS.some((field) => tf[field] > 0)).length
if (matching === 0) continue
const weightOfTerm = idf(matching, docs.length)
docs.forEach((doc, at) => {
const tf = perDoc[at]
if (tf === undefined) return
let score = 0
for (const field of FIELDS) {
if (tf[field] === 0) continue
score += WEIGHT[field] * saturate(tf[field], doc.fields[field].length, average[field])
}
scores.set(doc.id, (scores.get(doc.id) ?? 0) + weightOfTerm * score)
})
}
const ranked = docs
.map((doc) => ({ ...doc, score: scores.get(doc.id) ?? 0 }))
.filter((doc) => doc.score > 0)
.sort(compare)
return {
hits: ranked.slice(0, opts.limit).map(({ id, score }) => ({ id, score })),
total: ranked.length,
}
}
+37
View File
@@ -0,0 +1,37 @@
export function namespacesOf(ids: readonly string[], sep: string): ReadonlySet<string> {
const out = new Set<string>()
for (const id of ids) {
const parts = id.split(sep)
for (let depth = 1; depth < parts.length; depth++) out.add(parts.slice(0, depth).join(sep))
}
return out
}
export function under(namespace: string, ids: readonly string[], sep: string): string[] {
const prefix = `${namespace}${sep}`
return ids.filter((id) => id.startsWith(prefix))
}
export function byHead(
ids: readonly string[],
sep: string,
): ReadonlyMap<string, readonly string[]> {
const out = new Map<string, string[]>()
for (const id of [...ids].sort()) {
const at = id.indexOf(sep)
const head = at === -1 ? id : id.slice(0, at)
const rest = out.get(head) ?? []
if (at !== -1) rest.push(id.slice(at + 1))
out.set(head, rest)
}
return out
}
export function groupsOf(remainders: readonly string[], sep: string): string[] {
const groups = new Set<string>()
for (const rest of remainders) {
const at = rest.indexOf(sep)
if (at !== -1) groups.add(rest.slice(0, at))
}
return [...groups]
}
+140
View File
@@ -0,0 +1,140 @@
import { describe, expect, it } from 'vite-plus/test'
import { BaseError, HttpClientError, isBaseError, newError, unknownError } from './base'
import { ErrorCode, ExitCode } from './codes'
describe('BaseError', () => {
it('captures code, message, optional fields', () => {
const err = new HttpClientError({
code: ErrorCode.AuthExpired,
message: 'session expired',
hint: 'run difyctl auth login',
httpStatus: 401,
method: 'GET',
url: 'https://x/y',
})
expect(err.code).toBe(ErrorCode.AuthExpired)
expect(err.message).toBe('session expired')
expect(err.hint).toBe('run difyctl auth login')
expect(err.httpStatus).toBe(401)
expect(err.method).toBe('GET')
expect(err.url).toBe('https://x/y')
})
it('is an Error instance and instanceof BaseError', () => {
const err = newError(ErrorCode.Unknown, 'x')
expect(err).toBeInstanceOf(Error)
expect(err).toBeInstanceOf(BaseError)
})
it('exit() routes via code map', () => {
expect(newError(ErrorCode.AuthExpired, 'x').exit()).toBe(ExitCode.Auth)
expect(newError(ErrorCode.UsageInvalidFlag, 'x').exit()).toBe(ExitCode.Usage)
expect(newError(ErrorCode.CatalogUnavailable, 'x').exit()).toBe(ExitCode.Catalog)
})
it('toString without hint formats "<code>: <message>"', () => {
const err = newError(ErrorCode.AuthExpired, 'session expired')
expect(err.toString()).toBe('auth_expired: session expired')
})
it('toString with hint formats "<code>: <message> (hint: <hint>)"', () => {
const err = newError(ErrorCode.AuthExpired, 'session expired').withHint(
"run 'difyctl auth login'",
)
expect(err.toString()).toBe("auth_expired: session expired (hint: run 'difyctl auth login')")
})
it('builder methods return new instances; original unchanged', () => {
const original = newError(ErrorCode.Unknown, 'boom')
const hinted = original.withHint('try again')
expect(original.hint).toBeUndefined()
expect(hinted.hint).toBe('try again')
expect(hinted).not.toBe(original)
})
it('withHttpStatus + withRequest + wrap chain immutably', () => {
const cause = new Error('underlying')
const built = HttpClientError.from(newError(ErrorCode.NetworkConnection, 'timed out'))
.withHttpStatus(504)
.withRequest('POST', 'https://x/y')
.wrap(cause)
expect(built.httpStatus).toBe(504)
expect(built.method).toBe('POST')
expect(built.url).toBe('https://x/y')
expect(built.cause).toBe(cause)
})
it('wrap exposes cause via standard Error.cause property', () => {
const cause = new Error('underlying failure')
const wrapped = newError(ErrorCode.NetworkConnection, 'timed out').wrap(cause)
expect(wrapped.cause).toBe(cause)
})
it('isBaseError narrows unknown values', () => {
expect(isBaseError(newError(ErrorCode.Unknown, 'x'))).toBe(true)
expect(isBaseError(new Error('plain'))).toBe(false)
expect(isBaseError({ code: 'unknown' })).toBe(false)
expect(isBaseError(undefined)).toBe(false)
})
it('unknownError factory wraps cause and uses ErrorCode.Unknown', () => {
const cause = new Error('boom')
const err = unknownError('something failed', cause)
expect(err.code).toBe(ErrorCode.Unknown)
expect(err.cause).toBe(cause)
})
})
describe('error envelope', () => {
it('emits required fields only when minimal', () => {
const err = newError(ErrorCode.Unknown, 'boom')
expect(err.toEnvelope()).toEqual({
error: { code: 'unknown', message: 'boom' },
})
})
it('includes hint / http_status / method / url when present', () => {
const err = HttpClientError.from(newError(ErrorCode.NetworkConnection, 'timed out'))
.withHint('check your network')
.withHttpStatus(504)
.withRequest('POST', 'https://api.dify.ai/v1/x')
expect(err.toEnvelope()).toEqual({
error: {
code: 'network_connection',
message: 'timed out',
hint: 'check your network',
http_status: 504,
method: 'POST',
url: 'https://api.dify.ai/v1/x',
},
})
})
it('renderEnvelope returns a single-line JSON string', () => {
const err = newError(ErrorCode.AuthExpired, 'session expired').withHint(
'run difyctl auth login',
)
const out = JSON.stringify(err.toEnvelope())
expect(out).toBe(
'{"error":{"code":"auth_expired","message":"session expired","hint":"run difyctl auth login"}}',
)
expect(out).not.toContain('\n')
})
it('renderEnvelope output round-trips through JSON.parse to an ErrorEnvelope shape', () => {
const err = newError(ErrorCode.UsageInvalidFlag, 'bad flag').withHint('see --help')
const parsed = JSON.parse(JSON.stringify(err.toEnvelope()))
expect(parsed).toEqual({
error: { code: 'usage_invalid_flag', message: 'bad flag', hint: 'see --help' },
})
})
it('omits undefined optional fields entirely (no `hint: null`)', () => {
const err = newError(ErrorCode.ServerError, 'upstream broke')
const envelope = err.toEnvelope()
expect(envelope.error).not.toHaveProperty('hint')
expect(envelope.error).not.toHaveProperty('http_status')
expect(envelope.error).not.toHaveProperty('method')
expect(envelope.error).not.toHaveProperty('url')
})
})
+218
View File
@@ -0,0 +1,218 @@
import type { ErrorCodeValue, ExitCodeValue } from './codes'
import type { Hint } from '@/protocol/hint'
import { BINARY } from '@/version/info'
import { ErrorCode, exitFor } from './codes'
export const LOC_SEPARATOR = '.'
export type ServerErrorDetail = {
readonly type: string
readonly loc?: (string | number)[]
readonly msg: string
}
/** A detail the CLI reports; `field` is the input as the user typed it. */
export type ErrorDetail = ServerErrorDetail & { readonly field?: string }
export type ServerErrorBody = {
readonly code?: string
readonly message: string
readonly status?: number
readonly hint?: string
readonly hints?: Hint[]
readonly details?: ServerErrorDetail[]
}
export type ErrorEnvelope = {
error: {
code: string
message: string
hint?: string
details?: ErrorDetail[]
schema?: unknown
http_status?: number
method?: string
url?: string
raw_response?: string
server?: ServerErrorBody
}
}
export type BaseErrorOptions = {
readonly code: ErrorCodeValue
readonly message: string
readonly hint?: string
readonly cause?: unknown
readonly details?: ErrorDetail[]
readonly schema?: unknown
}
export class BaseError extends Error {
readonly code: ErrorCodeValue
readonly hint?: string
readonly details?: ErrorDetail[]
readonly schema?: unknown
constructor(opts: BaseErrorOptions) {
super(opts.message, opts.cause === undefined ? undefined : { cause: opts.cause })
this.name = 'BaseError'
this.code = opts.code
this.hint = opts.hint
this.details = opts.details
this.schema = opts.schema
Object.setPrototypeOf(this, new.target.prototype)
}
exit(): ExitCodeValue {
return exitFor(this.code)
}
override toString(): string {
return this.hint
? `${this.code}: ${this.message} (hint: ${this.hint})`
: `${this.code}: ${this.message}`
}
toEnvelope(): ErrorEnvelope {
const payload: ErrorEnvelope['error'] = {
code: this.code,
message: this.message,
}
if (this.hint !== undefined) payload.hint = this.hint
if (this.details !== undefined) payload.details = this.details
if (this.schema !== undefined) payload.schema = this.schema
return { error: payload }
}
withHint<T extends BaseError>(this: T, hint: string): T {
const Ctor = this.constructor as new (opts: BaseErrorOptions) => T
return new Ctor({ ...this.snapshot(), hint })
}
wrap<T extends BaseError>(this: T, cause: unknown): T {
const Ctor = this.constructor as new (opts: BaseErrorOptions) => T
return new Ctor({ ...this.snapshot(), cause })
}
protected snapshot(): BaseErrorOptions {
return {
code: this.code,
message: this.message,
hint: this.hint,
cause: this.cause,
details: this.details,
schema: this.schema,
}
}
}
export function newError(code: ErrorCodeValue, message: string): BaseError {
return new BaseError({ code, message })
}
export function isBaseError(value: unknown): value is BaseError {
return value instanceof BaseError
}
export function isHttpClientError(value: unknown): value is HttpClientError {
return value instanceof HttpClientError
}
export function unknownError(message: string, cause?: unknown): BaseError {
return new BaseError({ code: ErrorCode.Unknown, message, cause })
}
export const LOGIN_HINT = `run ${BINARY} help login`
export function notLoggedInMessage(reason?: string): string {
return reason === undefined ? 'not logged in' : `not logged in: ${reason}`
}
export function notLoggedIn(reason?: string): BaseError {
return new BaseError({
code: ErrorCode.NotLoggedIn,
message: notLoggedInMessage(reason),
hint: LOGIN_HINT,
})
}
type HttpClientErrorOptions = BaseErrorOptions & {
readonly httpStatus?: number
readonly method?: string
readonly url?: string
readonly rawResponse?: string
readonly serverError?: ServerErrorBody
}
export class HttpClientError extends BaseError {
readonly httpStatus?: number
readonly method?: string
readonly url?: string
readonly rawResponse?: string
readonly serverError?: ServerErrorBody
constructor(opts: HttpClientErrorOptions) {
super(opts)
this.httpStatus = opts.httpStatus
this.method = opts.method
this.url = opts.url
this.rawResponse = opts.rawResponse
this.serverError = opts.serverError
}
override toEnvelope(): ErrorEnvelope {
const envelope = super.toEnvelope()
if (this.httpStatus !== undefined) envelope.error.http_status = this.httpStatus
if (this.method !== undefined) envelope.error.method = this.method
if (this.url !== undefined) envelope.error.url = this.url
if (this.rawResponse !== undefined) envelope.error.raw_response = this.rawResponse
if (this.serverError !== undefined) envelope.error.server = this.serverError
// One details[] surface for both client- and server-authored rejections: the
// server's own details fill in only when this error didn't already have its own.
if (envelope.error.details === undefined && this.serverError?.details !== undefined)
envelope.error.details = this.serverError.details
return envelope
}
protected override snapshot(): HttpClientErrorOptions {
return {
...super.snapshot(),
httpStatus: this.httpStatus,
method: this.method,
url: this.url,
rawResponse: this.rawResponse,
serverError: this.serverError,
}
}
public static from(error: BaseError): HttpClientError {
return new HttpClientError({
code: error.code,
message: error.message,
hint: error.hint,
cause: error.cause,
details: error.details,
schema: error.schema,
})
}
withHttpStatus(httpStatus: number): HttpClientError {
return new HttpClientError({ ...this.snapshot(), httpStatus })
}
withRequest(method: string, url: string): HttpClientError {
return new HttpClientError({ ...this.snapshot(), method, url })
}
withRawResponse(rawResponse: string): HttpClientError {
if (!rawResponse) {
return this
}
return new HttpClientError({ ...this.snapshot(), rawResponse })
}
withServerError(serverError: ServerErrorBody): HttpClientError {
return new HttpClientError({ ...this.snapshot(), serverError })
}
}
@@ -0,0 +1,16 @@
import { expect, it } from 'vite-plus/test'
import { ALL_ERROR_CODES, ErrorCode, ExitCode, exitFor } from './codes'
it('maps every code to the frozen exit taxonomy', () => {
expect(exitFor(ErrorCode.NotLoggedIn)).toBe(ExitCode.Auth)
expect(exitFor(ErrorCode.AccessDenied)).toBe(ExitCode.Auth)
expect(exitFor(ErrorCode.InputInvalid)).toBe(ExitCode.Usage)
expect(exitFor(ErrorCode.UsageInvalidFlag)).toBe(ExitCode.Usage)
expect(exitFor(ErrorCode.CatalogUnavailable)).toBe(ExitCode.Catalog)
expect(exitFor(ErrorCode.UnknownOp)).toBe(ExitCode.Catalog)
expect(exitFor(ErrorCode.RateLimited)).toBe(ExitCode.RateLimited)
expect(exitFor(ErrorCode.ServerError)).toBe(ExitCode.Generic)
expect(exitFor('something_from_the_future')).toBe(ExitCode.Generic)
expect(new Set(Object.values(ExitCode))).toEqual(new Set([0, 1, 2, 4, 6, 7]))
for (const code of ALL_ERROR_CODES) expect([0, 1, 2, 4, 6, 7]).toContain(exitFor(code))
})
+57
View File
@@ -0,0 +1,57 @@
export const ErrorCode = {
NotLoggedIn: 'not_logged_in',
AuthExpired: 'auth_expired',
AccessDenied: 'access_denied',
UsageInvalidFlag: 'usage_invalid_flag',
UsageMissingArg: 'usage_missing_arg',
InputInvalid: 'input_invalid',
ConfigInvalidKey: 'config_invalid_key',
ConfigInvalidValue: 'config_invalid_value',
CatalogUnavailable: 'catalog_unavailable',
UnknownOp: 'unknown_op',
NetworkConnection: 'network_connection',
RateLimited: 'rate_limited',
ServerError: 'server_error',
KeyringUnavailable: 'keyring_unavailable',
SkillMissing: 'skill_missing',
Unknown: 'unknown',
} as const
export type ErrorCodeValue = (typeof ErrorCode)[keyof typeof ErrorCode]
export const ExitCode = {
Success: 0,
Generic: 1,
Usage: 2,
Auth: 4,
Catalog: 6,
// Distinct from Generic so wrappers can tell "rate limited, retry later" from a hard failure.
RateLimited: 7,
} as const
export type ExitCodeValue = (typeof ExitCode)[keyof typeof ExitCode]
const CODE_TO_EXIT: Readonly<Record<ErrorCodeValue, ExitCodeValue>> = {
not_logged_in: ExitCode.Auth,
auth_expired: ExitCode.Auth,
access_denied: ExitCode.Auth,
usage_invalid_flag: ExitCode.Usage,
usage_missing_arg: ExitCode.Usage,
input_invalid: ExitCode.Usage,
config_invalid_key: ExitCode.Usage,
config_invalid_value: ExitCode.Usage,
catalog_unavailable: ExitCode.Catalog,
unknown_op: ExitCode.Catalog,
network_connection: ExitCode.Generic,
rate_limited: ExitCode.RateLimited,
server_error: ExitCode.Generic,
keyring_unavailable: ExitCode.Generic,
skill_missing: ExitCode.Generic,
unknown: ExitCode.Generic,
}
export function exitFor(code: string): ExitCodeValue {
return (CODE_TO_EXIT as Record<string, ExitCodeValue>)[code] ?? ExitCode.Generic
}
export const ALL_ERROR_CODES: readonly ErrorCodeValue[] = Object.values(ErrorCode)
@@ -0,0 +1,93 @@
import { expect, it } from 'vite-plus/test'
import { ioService } from '@/plugins/io'
import { OutputMode } from '@/plugins/output'
import { bufferStreams } from '@/sys/io/streams'
import { BaseError, HttpClientError } from './base'
import { ErrorCode } from './codes'
import { printEnvelope } from './envelope'
it('prints one JSON line with details and schema and returns the exit code', async () => {
const streams = bufferStreams()
const code = await printEnvelope(
new BaseError({
code: ErrorCode.InputInvalid,
message: 'bad',
details: [{ type: 'required', loc: ['inputs'], msg: 'missing' }],
schema: { type: 'object' },
}),
ioService(streams, { out: OutputMode.Json, err: OutputMode.Json }),
{ verbose: false },
)
expect(code).toBe(2)
expect(JSON.parse(streams.errBuf())).toEqual({
error: {
code: 'input_invalid',
message: 'bad',
details: [{ type: 'required', loc: ['inputs'], msg: 'missing' }],
schema: { type: 'object' },
},
})
})
it('hides raw_response unless verbose and redacts the bearer', async () => {
const err = new HttpClientError({
code: ErrorCode.ServerError,
message: 'x',
httpStatus: 500,
rawResponse: 'Bearer abc',
})
const quiet = bufferStreams()
await printEnvelope(err, ioService(quiet, { out: OutputMode.Json, err: OutputMode.Json }), {
verbose: false,
})
expect(JSON.parse(quiet.errBuf()).error.raw_response).toBeUndefined()
const loud = bufferStreams()
await printEnvelope(err, ioService(loud, { out: OutputMode.Json, err: OutputMode.Json }), {
verbose: true,
})
expect(JSON.parse(loud.errBuf()).error.raw_response).toBe('Bearer [redacted]')
})
it('offers --verbose in text when the raw response is hidden, and shows it redacted when asked', async () => {
const err = new HttpClientError({
code: ErrorCode.ServerError,
message: 'boom',
httpStatus: 500,
rawResponse: 'Bearer abc body',
})
const quiet = bufferStreams()
await printEnvelope(err, ioService(quiet, { out: OutputMode.Json, err: OutputMode.Text }), {
verbose: false,
})
expect(quiet.errBuf()).toContain('hint: run again with --verbose to see the raw server response')
expect(quiet.errBuf()).not.toContain('raw_response:')
const loud = bufferStreams()
await printEnvelope(err, ioService(loud, { out: OutputMode.Json, err: OutputMode.Text }), {
verbose: true,
})
expect(loud.errBuf()).toContain('raw_response: Bearer [redacted] body')
expect(loud.errBuf()).not.toContain('--verbose to see')
})
it('wraps unknown errors as unknown with exit 1', async () => {
const streams = bufferStreams()
const code = await printEnvelope(
new Error('boom'),
ioService(streams, { out: OutputMode.Json, err: OutputMode.Json }),
{ verbose: false },
)
expect(code).toBe(1)
expect(JSON.parse(streams.errBuf()).error.code).toBe('unknown')
})
it('renders the text form on stderr when the err channel is text, exit code unchanged', async () => {
const streams = bufferStreams()
const code = await printEnvelope(
new BaseError({ code: ErrorCode.InputInvalid, message: 'bad' }),
ioService(streams, { out: OutputMode.Json, err: OutputMode.Text }),
{ verbose: false },
)
expect(code).toBe(2)
expect(streams.errBuf()).toBe('input_invalid: bad\n')
})
+53
View File
@@ -0,0 +1,53 @@
import type { ErrorEnvelope } from './base'
import type { IOService } from '@/plugins/io'
import { redactBearer } from '@/errors/sanitize'
import { Channel } from '@/plugins/io'
import { view } from '@/sys/io/view'
import { BaseError } from './base'
import { ErrorCode, ExitCode, exitFor } from './codes'
import { renderEnvelope } from './format'
import { errorMessage } from './message'
const EPIPE = 'EPIPE'
/** A reader that closed stdout (`| head`) ends a run; it never fails it. */
export function isBrokenPipe(err: unknown): boolean {
return err instanceof Error && (err as NodeJS.ErrnoException).code === EPIPE
}
function envelopeFor(err: unknown): ErrorEnvelope {
if (err instanceof BaseError) return err.toEnvelope()
return {
error: {
code: ErrorCode.Unknown,
message: errorMessage(err),
},
}
}
// The text form reads the whole envelope: a hidden raw response is what makes it offer
// --verbose. Only the JSON form drops the body, and both see it redacted.
function jsonForm(envelope: ErrorEnvelope, verbose: boolean): ErrorEnvelope {
if (verbose) return envelope
const error = { ...envelope.error }
delete error.raw_response
return { error }
}
export async function printEnvelope(
err: unknown,
io: IOService,
opts: { readonly verbose: boolean },
): Promise<number> {
if (isBrokenPipe(err)) return ExitCode.Success
const envelope = envelopeFor(err)
const raw = envelope.error.raw_response
if (raw !== undefined) envelope.error.raw_response = redactBearer(raw)
await io.emit(
view(jsonForm(envelope, opts.verbose), (style) => renderEnvelope(envelope, style, opts)),
Channel.Err,
)
return exitFor(envelope.error.code)
}
Loaded 100 of 15831 files, more files were not shown because too many files have changed in this diff. Show more