@kweaver-ai/kweaver-sdk 0.7.1 → 0.7.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +34 -4
  2. package/README.zh.md +27 -2
  3. package/dist/api/datasources.d.ts +7 -0
  4. package/dist/api/datasources.js +8 -0
  5. package/dist/api/skills.js +10 -8
  6. package/dist/api/toolboxes.d.ts +2 -0
  7. package/dist/api/toolboxes.js +2 -1
  8. package/dist/cli.js +65 -17
  9. package/dist/commands/auth.js +85 -10
  10. package/dist/commands/bkn-ops.d.ts +6 -1
  11. package/dist/commands/bkn-ops.js +202 -93
  12. package/dist/commands/bkn-utils.d.ts +26 -2
  13. package/dist/commands/bkn-utils.js +66 -9
  14. package/dist/commands/config.js +8 -0
  15. package/dist/commands/context-loader.js +112 -36
  16. package/dist/commands/dataflow.js +194 -20
  17. package/dist/commands/ds.d.ts +23 -1
  18. package/dist/commands/ds.js +135 -27
  19. package/dist/commands/import-csv.d.ts +0 -2
  20. package/dist/commands/import-csv.js +2 -4
  21. package/dist/commands/skill.js +26 -6
  22. package/dist/commands/tool.d.ts +1 -0
  23. package/dist/commands/tool.js +12 -0
  24. package/dist/config/stateless.d.ts +13 -0
  25. package/dist/config/stateless.js +20 -0
  26. package/dist/config/store.d.ts +1 -0
  27. package/dist/config/store.js +17 -0
  28. package/dist/resources/toolboxes.d.ts +2 -0
  29. package/dist/templates/bkn/document/manifest.json +12 -0
  30. package/dist/templates/bkn/document/template.json +757 -0
  31. package/dist/templates/dataflow/unstructured/manifest.json +11 -0
  32. package/dist/templates/dataflow/unstructured/template.json +63 -0
  33. package/dist/templates/dataset/document/manifest.json +10 -0
  34. package/dist/templates/dataset/document/template.json +23 -0
  35. package/dist/templates/dataset/document-content/manifest.json +10 -0
  36. package/dist/templates/dataset/document-content/template.json +29 -0
  37. package/dist/templates/dataset/document-element/manifest.json +10 -0
  38. package/dist/templates/dataset/document-element/template.json +21 -0
  39. package/dist/utils/skill-bundle.d.ts +5 -0
  40. package/dist/utils/skill-bundle.js +74 -0
  41. package/dist/utils/template-loader.d.ts +40 -0
  42. package/dist/utils/template-loader.js +129 -0
  43. package/package.json +2 -1
package/README.md CHANGED
@@ -31,7 +31,7 @@ export KWEAVER_BASE_URL=https://your-kweaver-instance.com
31
31
  export KWEAVER_TOKEN=your-token
32
32
  ```
33
33
 
34
- With both set, API commands use that token even if you never ran `auth login`. You can also run **`kweaver auth status`**, **`kweaver auth whoami`** (supports `--json`), and **`kweaver config show`** when there is **no** current platform in `~/.kweaver/`. In env-token mode, `whoami` resolves the bound identity from EACP `/api/eacp/v1/user/get` and prints `Type` (user/app), `User ID`, `Account` and `Name`; this works for both opaque and JWT tokens. If EACP is unreachable, the CLI falls back to local JWT decode and prints a short hint when the token is opaque.
34
+ With both set, API commands use that token even if you never ran `auth login`. The same applies to **`kweaver --base-url <url> --token <access-token> <command>`** (stateless flag mode; see [Stateless token mode](#stateless-token-mode)). You can also run **`kweaver auth status`**, **`kweaver auth whoami`** (supports `--json`), and **`kweaver config show`** when there is **no** current platform in `~/.kweaver/`. In env-token mode, `whoami` resolves the bound identity from EACP `/api/eacp/v1/user/get` and prints `Type` (user/app), `User ID`, `Account` and `Name`; this works for both opaque and JWT tokens. If EACP is unreachable, the CLI falls back to local JWT decode and prints a short hint when the token is opaque.
35
35
 
36
36
  `kweaver config list-bd` lists business domains for the current user. App (service) tokens are not bound to an end-user — when the backend rejects the call with `401 invalid user_id`, the CLI re-checks the token type via EACP and, if confirmed `type:"app"`, replaces the cryptic backend body with `This command does not support app accounts.`. Use a user token (interactive `auth login`) for user-bound endpoints.
37
37
 
@@ -188,10 +188,12 @@ kweaver bkn action-log list/get/cancel
188
188
  kweaver agent list/get/create/update/delete/chat/sessions/history/publish/unpublish
189
189
  kweaver skill list/market/get/register/status/delete/content/read-file/download/install
190
190
  kweaver vega health/stats/inspect/sql/catalog/resource/connector-type
191
- kweaver context-loader config set/use/list/show
192
- kweaver context-loader search-schema/tool-call/kn-search/query-object-instance/find-skills/...
191
+ kweaver context-loader tools|resources|templates|prompts <kn-id>
192
+ kweaver context-loader search-schema|tool-call|kn-search|kn-schema-search <kn-id> <query|name> [...]
193
+ kweaver context-loader query-object-instance|query-instance-subgraph|get-logic-properties|get-action-info|find-skills <kn-id> ...
194
+ kweaver context-loader config set/use/list/show (deprecated; <kn-id> may be omitted to fall back to saved config)
193
195
  kweaver toolbox create/list/publish/unpublish/delete
194
- kweaver tool upload/list/enable/disable
196
+ kweaver tool upload/list/enable/disable/execute/debug (execute and debug accept --path for OpenAPI path params)
195
197
  kweaver call <path> [-X METHOD] [-d BODY] [-H header] [-F key=value]
196
198
  ```
197
199
 
@@ -240,6 +242,11 @@ kweaver tool upload --toolbox <BOX_ID> ./openapi.json
240
242
  # 3. Publish the toolbox and enable the tool
241
243
  kweaver toolbox publish <BOX_ID>
242
244
  kweaver tool enable --toolbox <BOX_ID> <TOOL_ID>
245
+
246
+ # Invoke / debug: envelope supports `--header`, `--query`, `--body`, and **`--path`**
247
+ # for OpenAPI `{param}` placeholders (required for paths like `/data-views/{id}`).
248
+ kweaver tool debug --toolbox <BOX_ID> <TOOL_ID> \
249
+ --path '{"id":"<DATA_VIEW_UUID>"}' [--body '<json>']
243
250
  ```
244
251
 
245
252
  **No-auth platforms:** If OAuth is not enabled, use `kweaver auth <url> --no-auth` (or run a normal `auth login`; a **404** on `POST /oauth2/clients` switches to no-auth automatically). Credentials are still saved under `~/.kweaver/` and work with `auth use` / `auth list`. Optional: `KWEAVER_NO_AUTH=1` with `KWEAVER_BASE_URL` when no token env is set. SDK: `new KWeaverClient({ baseUrl, auth: false })` or `kweaver.configure({ baseUrl, auth: false })`.
@@ -251,10 +258,33 @@ kweaver tool enable --toolbox <BOX_ID> <TOOL_ID>
251
258
  | `KWEAVER_BASE_URL` | KWeaver instance URL |
252
259
  | `KWEAVER_BUSINESS_DOMAIN` | Business domain identifier |
253
260
  | `KWEAVER_TOKEN` | Access token |
261
+ | `KWEAVER_TOKEN_SOURCE` | Internal sentinel set by the CLI when `--token` is passed; do not set manually |
254
262
  | `KWEAVER_NO_AUTH` | Set to `1`/`true`/`yes` to use no-auth sentinel when `KWEAVER_TOKEN` is unset (with `KWEAVER_BASE_URL` or active platform) |
255
263
  | `KWEAVER_TLS_INSECURE` | Set to `1` or `true` to skip TLS certificate verification for all HTTPS in the process (dev only; prefer `kweaver auth … --insecure` which saves per platform) |
256
264
  | `NODE_TLS_REJECT_UNAUTHORIZED` | Node.js built-in TLS switch: set to `0` to skip certificate verification for HTTPS in this process. The `kweaver` CLI sets this when `KWEAVER_TLS_INSECURE` is set or the saved token has insecure TLS (same scope as above; dev only). |
257
265
 
266
+ ### Stateless token mode
267
+
268
+ Pass an access token via `--token` for fully stateless invocations (no read or write of `~/.kweaver/` for that token):
269
+
270
+ ```bash
271
+ kweaver --base-url https://platform.example.com --token "$TOK" bkn list
272
+ ```
273
+
274
+ Resolution order:
275
+
276
+ | Source | base-url | token |
277
+ |--------|----------|-------|
278
+ | flag | `--base-url` | `--token` |
279
+ | env | `KWEAVER_BASE_URL` | `KWEAVER_TOKEN` |
280
+ | disk | active platform | OAuth session (refreshable) |
281
+
282
+ When `--token` is used, write-disk commands (`auth login` / `logout` / `use` / `delete` / `switch`, `config set-bd`, the entire `context-loader config` group) error out — drop `--token` or use `kweaver auth login` for a saved session.
283
+
284
+ `auth whoami` / `auth status` distinguish the two stateless modes: `Source: CLI (flag: --token)` for flag mode, `env (KWEAVER_TOKEN)` for env mode (`whoami --json` uses `"source": "flag"` vs `"source": "env"`).
285
+
286
+ `kweaver context-loader` runtime subcommands accept `<kn-id>` as the first positional (e.g. `kweaver context-loader tools <kn-id>`) or via the global `--kn-id <id>` / `-k <id>` flag, so they work in stateless mode without any saved config. The `context-loader config set|use|list|remove|show` management group is deprecated, prints a warning on use, and is disabled in its entirety under `--token`.
287
+
258
288
  ### TLS Certificate Troubleshooting
259
289
 
260
290
  If you encounter errors like `fetch failed`, `self-signed certificate`, or `UNABLE_TO_GET_ISSUER_CERT`, the target server likely uses a self-signed certificate or Kubernetes Ingress default fake certificate. Try the following in order of preference:
package/README.zh.md CHANGED
@@ -176,8 +176,10 @@ kweaver bkn action-log list/get/cancel
176
176
  kweaver agent list/get/chat/sessions/history
177
177
  kweaver skill list/market/get/register/status/delete/content/read-file/download/install
178
178
  kweaver vega health|stats|inspect|sql|catalog|resource|connector-type
179
- kweaver context-loader config set/use/list/show
180
- kweaver context-loader search-schema/tool-call/kn-search/query-object-instance/find-skills/...
179
+ kweaver context-loader tools|resources|templates|prompts <kn-id>
180
+ kweaver context-loader search-schema|tool-call|kn-search|kn-schema-search <kn-id> <query|name> [...]
181
+ kweaver context-loader query-object-instance|query-instance-subgraph|get-logic-properties|get-action-info|find-skills <kn-id> ...
182
+ kweaver context-loader config set/use/list/show (deprecated;省略 <kn-id> 时回退到已保存配置)
181
183
  kweaver call <path> [-X METHOD] [-d BODY] [-H header]
182
184
  ```
183
185
 
@@ -218,10 +220,33 @@ kweaver vega sql -d '{"resource_type":"mysql","query":"SELECT * FROM {{res-1}} L
218
220
  | `KWEAVER_BASE_URL` | KWeaver 实例地址 |
219
221
  | `KWEAVER_BUSINESS_DOMAIN` | 业务域标识 |
220
222
  | `KWEAVER_TOKEN` | 访问令牌 |
223
+ | `KWEAVER_TOKEN_SOURCE` | CLI 传入 `--token` 时由程序设置的内部标记;请勿手动设置 |
221
224
  | `KWEAVER_NO_AUTH` | 设为 `1`/`true`/`yes` 且未设置 `KWEAVER_TOKEN` 时使用 no-auth 占位(需 `KWEAVER_BASE_URL` 或已选平台) |
222
225
  | `KWEAVER_TLS_INSECURE` | 设为 `1` 或 `true` 时跳过 TLS 证书校验(仅开发;更推荐 `kweaver auth … --insecure` 以按平台持久化) |
223
226
  | `NODE_TLS_REJECT_UNAUTHORIZED` | Node.js 内置 TLS 开关:设为 `0` 时在本进程内跳过 HTTPS 证书校验。`kweaver` 在 `KWEAVER_TLS_INSECURE` 生效或已保存 token 为不安全 TLS 时会设置此项(范围同上;仅开发)。 |
224
227
 
228
+ ### Stateless token 模式
229
+
230
+ 通过 `--token` 传入访问令牌,该次调用对该 token 路径既不读也不写 `~/.kweaver/`:
231
+
232
+ ```bash
233
+ kweaver --base-url https://platform.example.com --token "$TOK" bkn list
234
+ ```
235
+
236
+ 来源优先级:
237
+
238
+ | 来源 | base-url | token |
239
+ |------|----------|-------|
240
+ | flag | `--base-url` | `--token` |
241
+ | env | `KWEAVER_BASE_URL` | `KWEAVER_TOKEN` |
242
+ | 磁盘 | active platform | OAuth 会话(可 refresh) |
243
+
244
+ `--token` 模式下会禁用写盘命令:`auth login` / `logout` / `use` / `delete` / `switch`、`config set-bd`、整个 `context-loader config` 子命令组 ——去掉 `--token` 或改用 `kweaver auth login`。
245
+
246
+ `auth whoami` / `auth status` 通过文案区分来源:flag 模式为 `CLI (flag: --token)`,env 模式为 `env (KWEAVER_TOKEN)`(`whoami --json` 为 `"source": "flag"` 与 `"source": "env"`)。
247
+
248
+ `kweaver context-loader` 运行时子命令将 `<kn-id>` 作为第一个位置参数(如 `kweaver context-loader tools <kn-id>`),也支持全局 `--kn-id <id>` / `-k <id>` flag,因此在 stateless 模式下可直接使用,无需任何持久化配置。`context-loader config set|use|list|remove|show` 管理子命令已被标记为 deprecated(每次调用打印警告),且在 `--token` 下整组被禁用。
249
+
225
250
  ### TLS 证书问题排查
226
251
 
227
252
  如果遇到 `fetch failed`、`self-signed certificate`、`UNABLE_TO_GET_ISSUER_CERT` 等 TLS 相关错误,通常是目标服务器使用了自签名证书或 Kubernetes Ingress 默认假证书。可按优先级尝试以下方案:
@@ -71,3 +71,10 @@ export interface ScanMetadataOptions {
71
71
  businessDomain?: string;
72
72
  }
73
73
  export declare function scanMetadata(options: ScanMetadataOptions): Promise<string>;
74
+ export interface ScanDatasourceMetadataOptions {
75
+ baseUrl: string;
76
+ accessToken: string;
77
+ id: string;
78
+ businessDomain?: string;
79
+ }
80
+ export declare function scanDatasourceMetadata(options: ScanDatasourceMetadataOptions): Promise<string>;
@@ -208,3 +208,11 @@ export async function scanMetadata(options) {
208
208
  }
209
209
  return taskId;
210
210
  }
211
+ // Looks up a datasource's type then triggers a metadata scan, so callers
212
+ // don't have to repeat the GET-then-scan dance whenever a flow needs the
213
+ // platform catalog refreshed (after import-csv, before discovering tables).
214
+ export async function scanDatasourceMetadata(options) {
215
+ const dsBody = await getDatasource(options);
216
+ const dsType = JSON.parse(dsBody).type ?? "mysql";
217
+ return scanMetadata({ ...options, dsType });
218
+ }
@@ -103,18 +103,20 @@ export async function updateSkillStatus(options) {
103
103
  }
104
104
  export async function registerSkillContent(options) {
105
105
  const url = buildUrl(options.baseUrl, `${SKILL_API_PREFIX}/skills`);
106
- const payload = {
107
- file_type: "content",
108
- file: options.content,
109
- };
106
+ const form = new FormData();
107
+ form.set("file_type", "content");
108
+ // Backend's gin form-binder rejects plain string field for `file`
109
+ // (typed json.RawMessage); needs an actual multipart file part with
110
+ // filename. See utils/gin.go GetBindMultipartFormRaw.
111
+ form.set("file", new Blob([options.content], { type: "text/markdown" }), "SKILL.md");
110
112
  if (options.source)
111
- payload.source = options.source;
113
+ form.set("source", options.source);
112
114
  if (options.extendInfo)
113
- payload.extend_info = options.extendInfo;
115
+ form.set("extend_info", JSON.stringify(options.extendInfo));
114
116
  const { body } = await fetchTextOrThrow(url, {
115
117
  method: "POST",
116
- headers: { ...baseHeaders(options), "content-type": "application/json" },
117
- body: JSON.stringify(payload),
118
+ headers: baseHeaders(options),
119
+ body: form,
118
120
  });
119
121
  return normalizeSkillId(unwrapEnvelope(body));
120
122
  }
@@ -63,6 +63,8 @@ export interface InvokeToolOptions extends BaseOpts {
63
63
  header?: Record<string, unknown>;
64
64
  /** Optional query params to forward. */
65
65
  query?: Record<string, unknown>;
66
+ /** Path parameter map for OpenAPI `{param}` placeholders (e.g. `{ id: "<uuid>" }`). */
67
+ path?: Record<string, unknown>;
66
68
  /** JSON body forwarded to the downstream tool. */
67
69
  body?: unknown;
68
70
  /** Per-call timeout in seconds; backend default applies when omitted. */
@@ -20,7 +20,7 @@ import { buildHeaders } from "./headers.js";
20
20
  // POST /tool-box/{box}/tool/{tool}/debug debug tool (envelope JSON)
21
21
  //
22
22
  // Envelope shape required by /proxy and /debug:
23
- // { "timeout": <s>, "header": {...}, "query": {...}, "body": {...} }
23
+ // { "timeout": <s>, "header": {...}, "query": {...}, "body": {...}, "path": {...} }
24
24
  // Flat-shape requests cause the forwarder to drop downstream Authorization
25
25
  // headers, which manifests as 401 "token expired" from the underlying tool.
26
26
  const PATH = "/api/agent-operator-integration/v1/tool-box";
@@ -145,6 +145,7 @@ function buildEnvelope(opts) {
145
145
  envelope.timeout = opts.timeout;
146
146
  envelope.header = opts.header ?? {};
147
147
  envelope.query = opts.query ?? {};
148
+ envelope.path = opts.path ?? {};
148
149
  envelope.body = opts.body ?? {};
149
150
  return JSON.stringify(envelope);
150
151
  }
package/dist/cli.js CHANGED
@@ -19,7 +19,7 @@ function printHelp() {
19
19
  console.log(`kweaver
20
20
 
21
21
  Usage:
22
- kweaver [--user <userId|username>] <command> [options]
22
+ kweaver [--base-url <url>] [--token <access-token>] [--user <userId|username>] <command> [options]
23
23
  kweaver --version | -V
24
24
  kweaver --help | -h
25
25
 
@@ -60,7 +60,12 @@ Usage:
60
60
  kweaver ds delete <id> [-y]
61
61
  kweaver ds tables <id> [--keyword X]
62
62
  kweaver ds connect <db_type> <host> <port> <database> --account X --password Y [--schema S] [--name N]
63
+ [--reuse-existing|--force-new]
63
64
 
65
+ kweaver dataflow templates [--json]
66
+ kweaver dataflow create-dataset --template <name> --set "key=value" [--json] [-bd value]
67
+ kweaver dataflow create-bkn --template <name> --set "key=value" [--json] [-bd value]
68
+ kweaver dataflow create (--template <name> --set "key=value" | <json>) [-bd value]
64
69
  kweaver dataflow list [-bd value]
65
70
  kweaver dataflow run <dagId> (--file <path> | --url <remote-url> --name <filename>) [-bd value]
66
71
  kweaver dataflow runs <dagId> [--since <date-like>] [-bd value]
@@ -115,7 +120,7 @@ Usage:
115
120
  kweaver tool enable|disable --toolbox <box-id> <tool-id>... [-bd value]
116
121
  kweaver tool execute|debug --toolbox <box-id> <tool-id>
117
122
  [--body '<json>'|--body-file <path>]
118
- [--header '<json>'] [--query '<json>'] [--timeout <s>]
123
+ [--header '<json>'] [--query '<json>'] [--path '<json>'] [--timeout <s>]
119
124
 
120
125
  kweaver vega health|stats|inspect
121
126
  kweaver vega catalog list|get|health|test-connection|discover|resources [options]
@@ -123,19 +128,34 @@ Usage:
123
128
  kweaver vega query execute|sql [options]
124
129
  kweaver vega connector-type list|get [options]
125
130
 
126
- kweaver context-loader config set|use|list|remove|show [options]
127
- kweaver context-loader tools|resources|templates|prompts [--cursor]
128
- kweaver context-loader resource <uri>
129
- kweaver context-loader prompt <name> [--args json]
130
- kweaver context-loader search-schema <query> [--scope object,relation,action,metric] [--max N]
131
- kweaver context-loader tool-call <name> --args '<json>'
132
- kweaver context-loader kn-search <query> [--only-schema] (compat HTTP)
133
- kweaver context-loader kn-schema-search <query> [--max N] (compat HTTP)
134
- kweaver context-loader query-object-instance|query-instance-subgraph|get-logic-properties|get-action-info|find-skills ...
131
+ kweaver context-loader config set|use|list|remove|show [options] (deprecated; not supported with --token)
132
+ kweaver context-loader tools|resources|templates|prompts <kn-id> [--cursor]
133
+ kweaver context-loader resource <kn-id> <uri>
134
+ kweaver context-loader prompt <kn-id> <name> [--args json]
135
+ kweaver context-loader search-schema <kn-id> <query> [--scope object,relation,action,metric] [--max N]
136
+ kweaver context-loader tool-call <kn-id> <name> --args '<json>'
137
+ kweaver context-loader kn-search <kn-id> <query> [--only-schema] (compat HTTP)
138
+ kweaver context-loader kn-schema-search <kn-id> <query> [--max N] (compat HTTP)
139
+ kweaver context-loader query-object-instance|query-instance-subgraph|get-logic-properties|get-action-info|find-skills <kn-id> ...
140
+ (omit <kn-id> to fall back to deprecated saved config)
135
141
  (alias: kweaver context ...)
136
142
 
137
143
  Global options:
138
- --user <id|name> Use a specific user's credentials for this command (env: KWEAVER_USER)
144
+ --base-url <url> Override platform base URL for this command (env: KWEAVER_BASE_URL)
145
+ --token <value> Override access token for this command (env: KWEAVER_TOKEN; disables write-to-disk commands)
146
+ --user <id|name> Use a specific user's credentials for this command, transient (env: KWEAVER_USER)
147
+
148
+ Multi-shell account isolation:
149
+ KWEAVER_PROFILE=<name> Scope state.json (active platform / active user) to a named
150
+ profile. Tokens under platforms/ are still shared, so each
151
+ profile reuses logins. Required for \`auth switch\` and
152
+ \`auth use\` (use --global to override). Name must match
153
+ [A-Za-z0-9_-]{1,64}.
154
+ KWEAVERC_CONFIG_DIR=<dir> Override the entire config root (~/.kweaver by default).
155
+ Use this for hard isolation (separate token store per shell).
156
+
157
+ For agents / multi-terminal scripts: prefer \`--user <id>\` (transient, no persistence)
158
+ over \`auth switch\` (persistent, requires KWEAVER_PROFILE).
139
159
  --pretty / --compact
140
160
  Toggle pretty-printed JSON output. Supported by every
141
161
  command that prints a JSON payload (default: pretty).
@@ -165,12 +185,40 @@ export async function run(argv) {
165
185
  !process.env.KWEAVER_TOKEN) {
166
186
  process.env.KWEAVER_TOKEN = NO_AUTH_TOKEN;
167
187
  }
168
- // Global --user flag: override active user for this invocation
169
- const userIdx = argv.indexOf("--user");
188
+ // Global flags consumed before subcommand dispatch.
189
+ // Pattern follows --user (legacy): each flag, if present, is removed from argv
190
+ // and projected into a process.env value that downstream resolvers already read.
170
191
  let filteredArgv = argv;
171
- if (userIdx !== -1 && userIdx + 1 < argv.length) {
172
- process.env.KWEAVER_USER = argv[userIdx + 1];
173
- filteredArgv = [...argv.slice(0, userIdx), ...argv.slice(userIdx + 2)];
192
+ function consumeFlag(flag) {
193
+ const idx = filteredArgv.indexOf(flag);
194
+ if (idx === -1 || idx + 1 >= filteredArgv.length)
195
+ return undefined;
196
+ const value = filteredArgv[idx + 1];
197
+ filteredArgv = [...filteredArgv.slice(0, idx), ...filteredArgv.slice(idx + 2)];
198
+ return value;
199
+ }
200
+ const userVal = consumeFlag("--user");
201
+ if (userVal)
202
+ process.env.KWEAVER_USER = userVal;
203
+ const tokenVal = consumeFlag("--token");
204
+ const baseUrlVal = consumeFlag("--base-url");
205
+ if (tokenVal) {
206
+ process.env.KWEAVER_TOKEN = tokenVal;
207
+ process.env.KWEAVER_TOKEN_SOURCE = "flag";
208
+ }
209
+ if (baseUrlVal) {
210
+ process.env.KWEAVER_BASE_URL = baseUrlVal;
211
+ }
212
+ // --token requires a base URL from somewhere; fail fast with guidance.
213
+ if (tokenVal && !process.env.KWEAVER_BASE_URL) {
214
+ const { getCurrentPlatform } = await import("./config/store.js");
215
+ if (!getCurrentPlatform()) {
216
+ console.error("--token requires a base URL. Provide one of:\n" +
217
+ " --base-url <url>\n" +
218
+ " export KWEAVER_BASE_URL=<url>\n" +
219
+ " kweaver auth login <url> (save once, reuse later)");
220
+ return 1;
221
+ }
174
222
  }
175
223
  const [command, ...rest] = filteredArgv;
176
224
  if (command === "--version" || command === "-V" || command === "version") {
@@ -1,8 +1,31 @@
1
1
  import { isNoAuth } from "../config/no-auth.js";
2
- import { autoSelectBusinessDomain, clearPlatformSession, deletePlatform, deleteUser, getActiveUser, getConfigDir, getCurrentPlatform, getPlatformAlias, hasPlatform, listPlatforms, listUserProfiles, loadClientConfig, loadTokenConfig, loadUserTokenConfig, resolveBusinessDomain, resolvePlatformIdentifier, resolveUserId, saveNoAuthPlatform, setActiveUser, setCurrentPlatform, setPlatformAlias, } from "../config/store.js";
2
+ import { assertNotStatelessForWrite } from "../config/stateless.js";
3
+ import { autoSelectBusinessDomain, clearPlatformSession, deletePlatform, deleteUser, getActiveUser, getConfigDir, getCurrentPlatform, getPlatformAlias, getProfileName, hasPlatform, listPlatforms, listUserProfiles, loadClientConfig, loadTokenConfig, loadUserTokenConfig, resolveBusinessDomain, resolvePlatformIdentifier, resolveUserId, saveNoAuthPlatform, setActiveUser, setCurrentPlatform, setPlatformAlias, } from "../config/store.js";
3
4
  import { decodeJwtPayload } from "../config/jwt.js";
4
5
  import { eacpModifyPassword } from "../auth/eacp-modify-password.js";
5
6
  import { buildCopyCommand, fetchEacpUserInfo, formatHttpError, InitialPasswordChangeRequiredError, normalizeBaseUrl, oauth2Login, oauth2PasswordSigninLogin, promptForUsername, promptForPassword, refreshTokenLogin, resolveActivePlatform, } from "../auth/oauth.js";
7
+ function consumeGlobalFlag(args) {
8
+ const idx = args.indexOf("--global");
9
+ if (idx === -1)
10
+ return { args, isGlobal: false };
11
+ return { args: [...args.slice(0, idx), ...args.slice(idx + 1)], isGlobal: true };
12
+ }
13
+ function requireProfileOrGlobal(command, isGlobal) {
14
+ if (isGlobal)
15
+ return null;
16
+ try {
17
+ if (getProfileName())
18
+ return null;
19
+ }
20
+ catch (err) {
21
+ return err instanceof Error ? err.message : String(err);
22
+ }
23
+ return (`kweaver auth ${command} mutates the active account globally and would affect every shell using ~/.kweaver.\n` +
24
+ `Pick one:\n` +
25
+ ` - Transient: prepend \`--user <id|name>\` (or \`KWEAVER_USER=<id>\`) to the command you actually want to run; no persistent switch.\n` +
26
+ ` - Persistent (this shell only): \`export KWEAVER_PROFILE=<name>\`, then re-run.\n` +
27
+ ` - Intentionally global (CI / single-user setup): re-run with \`--global\`.`);
28
+ }
6
29
  export async function runAuthCommand(args) {
7
30
  const target = args[0];
8
31
  const rest = args.slice(1);
@@ -71,6 +94,13 @@ Login options:
71
94
  const LOGIN_SUBCOMMANDS = new Set(["status", "list", "use", "delete", "logout", "export", "whoami", "users", "switch"]);
72
95
  if (target && !LOGIN_SUBCOMMANDS.has(target)) {
73
96
  try {
97
+ try {
98
+ assertNotStatelessForWrite("auth login");
99
+ }
100
+ catch (err) {
101
+ console.error(err instanceof Error ? err.message : String(err));
102
+ return 1;
103
+ }
74
104
  const normalizedTarget = normalizeBaseUrl(target);
75
105
  const alias = readOption(args, "--alias");
76
106
  let username = readOption(args, "--username") ?? readOption(args, "-u");
@@ -268,7 +298,8 @@ Login options:
268
298
  }
269
299
  console.log(`Config directory: ${getConfigDir()}`);
270
300
  console.log(`Platform: ${active.url} (KWEAVER_BASE_URL)`);
271
- console.log(`Token present: yes (KWEAVER_TOKEN)`);
301
+ const tokenProvenance = process.env.KWEAVER_TOKEN_SOURCE === "flag" ? "CLI (flag: --token)" : "KWEAVER_TOKEN";
302
+ console.log(`Token present: yes (${tokenProvenance})`);
272
303
  console.log(`Refresh token: n/a (env)`);
273
304
  return 0;
274
305
  }
@@ -348,16 +379,29 @@ Login options:
348
379
  return 0;
349
380
  }
350
381
  if (target === "use") {
351
- const resolvedTarget = args[1] ? resolvePlatformIdentifier(args[1]) : "";
382
+ const { args: useArgs, isGlobal } = consumeGlobalFlag(args);
383
+ const refusal = requireProfileOrGlobal("use", isGlobal);
384
+ if (refusal !== null) {
385
+ console.error(refusal);
386
+ return 1;
387
+ }
388
+ const resolvedTarget = useArgs[1] ? resolvePlatformIdentifier(useArgs[1]) : "";
352
389
  const useTarget = resolvedTarget && /^https?:\/\//.test(resolvedTarget) ? normalizeBaseUrl(resolvedTarget) : resolvedTarget;
353
390
  if (!useTarget) {
354
- console.error("Usage: kweaver auth use <platform-url|alias>");
391
+ console.error("Usage: kweaver auth use [--global] <platform-url|alias>");
355
392
  return 1;
356
393
  }
357
394
  if (!hasPlatform(useTarget)) {
358
395
  console.error(`No saved token for ${useTarget}. Run \`kweaver auth login ${useTarget}\` first.`);
359
396
  return 1;
360
397
  }
398
+ try {
399
+ assertNotStatelessForWrite("auth use");
400
+ }
401
+ catch (err) {
402
+ console.error(err instanceof Error ? err.message : String(err));
403
+ return 1;
404
+ }
361
405
  setCurrentPlatform(useTarget);
362
406
  console.log(`Current platform: ${useTarget}`);
363
407
  return 0;
@@ -375,6 +419,13 @@ Login options:
375
419
  console.error(`No saved token for ${deleteTarget}.`);
376
420
  return 1;
377
421
  }
422
+ try {
423
+ assertNotStatelessForWrite("auth delete");
424
+ }
425
+ catch (err) {
426
+ console.error(err instanceof Error ? err.message : String(err));
427
+ return 1;
428
+ }
378
429
  if (deleteUserArg) {
379
430
  const deleteUserId = resolveUserId(deleteTarget, deleteUserArg) ?? deleteUserArg;
380
431
  deleteUser(deleteTarget, deleteUserId);
@@ -404,6 +455,13 @@ Login options:
404
455
  console.error(`No saved token for ${logoutTarget}.`);
405
456
  return 1;
406
457
  }
458
+ try {
459
+ assertNotStatelessForWrite("auth logout");
460
+ }
461
+ catch (err) {
462
+ console.error(err instanceof Error ? err.message : String(err));
463
+ return 1;
464
+ }
407
465
  const logoutUserId = logoutUserArg ? resolveUserId(logoutTarget, logoutUserArg) ?? logoutUserArg : undefined;
408
466
  clearPlatformSession(logoutTarget, logoutUserId);
409
467
  const userHint = logoutUserId ? ` (user: ${logoutUserId})` : "";
@@ -460,18 +518,25 @@ You can use either userId or username with --user in switch/logout/delete.`);
460
518
  }
461
519
  function runAuthSwitchCommand(args) {
462
520
  if (args[0] === "--help" || args[0] === "-h") {
463
- console.log(`kweaver auth switch [platform-url|alias] --user <userId|username>
521
+ console.log(`kweaver auth switch [--global] [platform-url|alias] --user <userId|username>
464
522
 
465
523
  Switch the active user for a platform.
466
524
  You can specify either the userId (sub claim) or the username (preferred_username from id_token).`);
467
525
  return 0;
468
526
  }
469
- const userArg = readOption(args, "--user");
527
+ const { args: switchArgs, isGlobal } = consumeGlobalFlag(args);
528
+ const refusal = requireProfileOrGlobal("switch", isGlobal);
529
+ if (refusal !== null) {
530
+ console.error(refusal);
531
+ return 1;
532
+ }
533
+ const cleanedArgs = switchArgs;
534
+ const userArg = readOption(cleanedArgs, "--user") ?? process.env.KWEAVER_USER;
470
535
  if (!userArg) {
471
- console.error("Usage: kweaver auth switch [platform-url|alias] --user <userId|username>");
536
+ console.error("Usage: kweaver auth switch [--global] [platform-url|alias] --user <userId|username>");
472
537
  return 1;
473
538
  }
474
- const filteredArgs = args.filter((a) => a !== "--user" && a !== userArg);
539
+ const filteredArgs = cleanedArgs.filter((a) => a !== "--user" && a !== userArg);
475
540
  const platform = resolvePlatformArg(filteredArgs);
476
541
  if (!platform) {
477
542
  console.error("No active platform. Run `kweaver auth login <platform-url>` first.");
@@ -487,6 +552,13 @@ You can specify either the userId (sub claim) or the username (preferred_usernam
487
552
  }
488
553
  return 1;
489
554
  }
555
+ try {
556
+ assertNotStatelessForWrite("auth switch");
557
+ }
558
+ catch (err) {
559
+ console.error(err instanceof Error ? err.message : String(err));
560
+ return 1;
561
+ }
490
562
  setActiveUser(platform, resolvedId);
491
563
  const profiles = listUserProfiles(platform);
492
564
  const profile = profiles.find((p) => p.userId === resolvedId);
@@ -535,7 +607,10 @@ Options:
535
607
  // complete picture without forcing them to pick a mode.
536
608
  const jwtPayload = decodeJwtPayload(accessToken);
537
609
  if (jsonOutput) {
538
- const out = { platform: envUrl, source: "env" };
610
+ const out = {
611
+ platform: envUrl,
612
+ source: process.env.KWEAVER_TOKEN_SOURCE === "flag" ? "flag" : "env",
613
+ };
539
614
  if (userInfo)
540
615
  out.userInfo = userInfo;
541
616
  if (jwtPayload)
@@ -544,7 +619,7 @@ Options:
544
619
  return 0;
545
620
  }
546
621
  console.log(`Platform: ${envUrl}`);
547
- console.log(`Source: env (KWEAVER_TOKEN)`);
622
+ console.log(`Source: ${process.env.KWEAVER_TOKEN_SOURCE === "flag" ? "CLI (flag: --token)" : "env (KWEAVER_TOKEN)"}`);
548
623
  if (userInfo) {
549
624
  console.log(`Type: ${userInfo.type}`);
550
625
  console.log(`User ID: ${userInfo.id}`);
@@ -1,4 +1,6 @@
1
1
  import { type BknEncodingImportOptions } from "../utils/bkn-encoding.js";
2
+ export declare const BKN_OBJECT_NAME_MAX_LENGTH = 40;
3
+ export declare function assertValidBknObjectNames(names: string[], context: string): void;
2
4
  export declare function parseKnBuildArgs(args: string[]): {
3
5
  knId: string;
4
6
  wait: boolean;
@@ -30,10 +32,12 @@ export declare function parseKnCreateFromDsArgs(args: string[]): {
30
32
  dsId: string;
31
33
  name: string;
32
34
  tables: string[];
35
+ pkMap: Record<string, string>;
33
36
  build: boolean;
34
37
  timeout: number;
35
38
  businessDomain: string;
36
39
  pretty: boolean;
40
+ noRollback: boolean;
37
41
  };
38
42
  /** Generate a BKN ObjectType YAML markdown file for a table. */
39
43
  export declare function generateObjectTypeBkn(tableName: string, dvId: string, pk: string, dk: string, columns: Array<{
@@ -48,10 +52,11 @@ export declare function parseKnCreateFromCsvArgs(args: string[]): {
48
52
  tablePrefix: string;
49
53
  batchSize: number;
50
54
  tables: string[];
55
+ pkMap: Record<string, string>;
51
56
  build: boolean;
52
- recreate: boolean;
53
57
  timeout: number;
54
58
  businessDomain: string;
59
+ noRollback: boolean;
55
60
  };
56
61
  export declare function runKnCreateFromCsvCommand(args: string[]): Promise<number>;
57
62
  export interface ActionScheduleParsed {