@aliyunrds/ctxdb 1.0.8-beta.3 → 1.0.8

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.
package/README.md CHANGED
@@ -17,9 +17,100 @@ Config and logs live under `~/.ctxdb/`. `~/.ctxdb/ctxdb.json` is one file, but r
17
17
 
18
18
  ## Install
19
19
 
20
+ ### Public Device Flow login (requires the enabled Core/API phase 2 service)
21
+
22
+ ```sh
23
+ ctxdb login --agent codex
24
+ # Authorize in the console; this command also installs hooks/skills and validates the connection.
25
+ # To share one login across several Agents instead:
26
+ ctxdb login --base-url https://<core-host> --no-browser
27
+ # Complete the displayed user code through the console/independent POP client.
28
+ ctxdb setup --agent codex
29
+ ctxdb setup --agent opencode
30
+ ctxdb auth status --all --json
31
+ # Explicitly choose another identity for one Agent:
32
+ ctxdb login --agent codex --base-url https://<core-host>
33
+ ctxdb setup --agent codex --login default
34
+ ctxdb auth unbind --agent codex
35
+ ctxdb logout --login default --yes --json
36
+ ```
37
+
38
+ Public login uses Core Device Flow; `--device-code` selects the same default flow.
39
+ The scope is always `default`, following current Member permissions and resource ACLs;
40
+ `--scope` is not accepted. Login for a non-default Agent also runs setup, using the endpoint
41
+ selected by that login. Default login and `--login` reauthorization only manage authentication.
42
+ If setup fails, login exits nonzero with `authenticated: true` and setup diagnostics; the saved
43
+ session remains available for `ctxdb setup --agent <name>` to retry. Hermes approval requirements
44
+ remain explicit, and successful setup includes the usual host restart/trust reminders.
45
+ Ordinary setup preserves
46
+ existing authentication and binds the default login only for an Agent without an authentication
47
+ choice. Without `--base-url`, setup resets the selected credential's DATA endpoint to
48
+ `https://api.cn-hangzhou.agentcontext.aliyuncs.com`, including existing keys and logins.
49
+ All Agents sharing that login use its updated endpoint. `setup --all` applies the same policy to detected Agents.
50
+ An explicit invalid `--base-url` (including a missing or empty value) fails before configuration
51
+ changes and suggests the current production URL; it never acts like an omitted option.
52
+
53
+ New credentials share `credentials.json` version 2. Every record has exactly
54
+ `kind`, `payload`, and `metadata`; kinds are `api-key` and `oauth-session`.
55
+ `payload` contains only the API Key or AT/RT. Service addresses, identity, scope,
56
+ expiry and lifecycle fields live in `metadata` and remain validated atomically
57
+ with the credential. Uncertain refreshes retain metadata with an empty payload; retired logins are deleted.
58
+ Agent API keys use `credential_ref`, and shared sessions use
59
+ `access_credential -> logins.<ID>.credential_ref`. New login IDs use the creating Agent
60
+ and eight random hexadecimal characters (for example, `default-e0c3f323` or `codex-a71e900a`).
61
+ Sharing and reauthorizing the same login keep its ID. Ownership, state and revision live in
62
+ metadata. Referenced credentials also own their service address: Agent sections no longer
63
+ write `base_url`. Leftover config addresses cannot redirect a referenced credential; explicit
64
+ address overrides must match its metadata. Legacy config keys and environment credentials
65
+ keep their existing address selection. No new secrets are written to `ctxdb.json` and no OAuth directory is created.
66
+ Released internal v1 credentials and legacy config API keys remain readable without
67
+ migration on ordinary reads. Unreleased OAuth-directory test sessions require login again.
68
+ See [unified credential storage and compatibility](../../docs/unified-credentials.md).
69
+
70
+ CLI, hooks and OpenCode use shared authentication resolution and one cross-process refresh lock.
71
+ Unbind only removes a local binding. `logout --agent` detaches that Agent, retaining the
72
+ session while another Agent uses it; the last logout deletes its login and credential records
73
+ and revokes the remote session. `logout --login` explicitly logs out all sharing Agents. Reauthorizing
74
+ default or `login --login <ID>` updates all Agents still sharing that login. Independent
75
+ `login --agent <name>` creates a new record and retires the previous session if it has no users.
76
+ Successful login and logout also collect historical unreferenced login records.
77
+ Logout performs this collection even when the selected Agent has no current login; unconfirmed
78
+ remote cleanup returns a failure status while active shared sessions and API keys are preserved.
79
+ Changes affecting other Agents list them and require confirmation (`--yes` for non-interactive execution).
80
+ Failed/ambiguous refresh, damaged references, origin mismatch and revoked sessions never fall back
81
+ to an older key or another login. Runtime environment credentials keep their original priority
82
+ and are not persisted; explicit auth switches reject masking environment overrides before writing.
83
+
84
+ Upgrade the CLI and the actual hooks/plugin artifacts together before enabling sharing.
85
+ New CLI reading old v2 configuration is supported; old CLI reading shared-login configuration is not.
86
+ See [共享登录、完整命令与兼容契约](../../docs/cli-shared-login.md) for migration and concurrency details.
87
+
88
+ The production Core origin `https://api.cn-hangzhou.agentcontext.aliyuncs.com` defaults to the console page
89
+ `https://rdsnext.console.aliyun.com/contextDbCliAuthorization/cn-hangzhou`. CLI appends the current
90
+ `user_code`; the console route uses the fixed `cn-hangzhou` region.
91
+ Ordinary DATA requests and artifact-only `upgrade` keep the configured origin, without endpoint fallback.
92
+ `setup` and every `login`, including reauthorization, use the default production origin unless
93
+ `--base-url` is supplied. Relogin no longer inherits the previous session's origin.
94
+ Explicitly selecting the legacy Core origin `https://context-database.aliyuncs.com` keeps the same console mapping.
95
+ Use `--base-url` to select the Core service and `--login-url` to supply the HTTPS console page
96
+ for this invocation. The latter does not change the service origin or persist a console mapping.
97
+ The legacy `--server` alias for `--base-url` remains accepted; do not pass both.
98
+ The optional sibling `device-environments.json` (`version: 1`, `environments: [{core_url,
99
+ authorization_url}]`) overrides the console page for an exactly matching Core origin.
100
+ The page must use HTTPS without credentials, query parameters or a fragment. Unmatched entries
101
+ retain the production default. Preproduction and custom Core origins have no built-in console
102
+ mapping: tests pass `--base-url` and `--login-url` explicitly, or use the code with the independent POP test client.
103
+ Console page priority is `--login-url`, then the local mapping, then the production default.
104
+ URLs never come from server discovery. When a console URL is available, login opens the default
105
+ browser and keeps polling. It always prints the URL and code; if opening fails, use that URL
106
+ manually. Pass `--no-browser` to print the link without opening a browser.
107
+
108
+ POSIX uses private files/directories; Windows validates an owner-only ACL using local PowerShell.
109
+ Native Windows acceptance remains separate from the macOS local test record.
110
+
20
111
  ### Internal browser-login distribution
21
112
 
22
- The same source also builds `@ali/ctxdb-internal`. That artifact alone
113
+ The same source also builds `@ali/ctxdb-internal`. Its existing prototype
23
114
  adds `ctxdb login --server <url>`, `ctxdb login --device-code`, `ctxdb logout`,
24
115
  and `ctxdb auth status`. The default login uses a browser loopback callback;
25
116
  `--device-code` supports remote or headless terminals. Both methods discover a
@@ -36,16 +127,16 @@ credential overrides the API key and DATA URL in the existing v2
36
127
  three while `ctxdb logout` rejects the two credential overrides, so command
37
128
  output cannot disagree with subsequent DATA requests. Re-login replaces the
38
129
  active connection and revokes the previous key after setup succeeds. The
39
- public `@aliyunrds/ctxdb` build does not contain or advertise these commands and
40
- continues to use `ctxdb setup` and the v2 config exactly as before. Build the
130
+ public `@aliyunrds/ctxdb` build uses the distinct Device Flow implementation above and
131
+ continues to support API-key setup. It never reads the internal credential store. Build the
41
132
  internal staging package with `pnpm build:internal`.
42
133
 
43
134
  The distinction is a compile-time distribution manifest, not a runtime
44
135
  environment-variable or file-existence check. The `public` manifest disables
45
- `interactiveLogin` and `managedCredentials`; the `internal` manifest enables
46
- both. The CLI hooks and the separately bundled OpenCode plugin receive the
136
+ internal-protocol flags `interactiveLogin` and `managedCredentials`, and enables `deviceFlow`;
137
+ the `internal` manifest enables the former two and disables `deviceFlow`. The CLI hooks and the separately bundled OpenCode plugin receive the
47
138
  same manifest, so installing a public build on a machine that happens to have
48
- `~/.ctxdb/credentials.json` does not make that build consume the file.
139
+ `~/.ctxdb/credentials.json` does not make the public build consume the internal active record.
49
140
 
50
141
  Internal users install the package from Ali NPM. The internal version is
51
142
  managed independently in `internal-release.json`; it does not inherit the
@@ -166,7 +257,7 @@ ctxdb setup --agent hermes --api-key ctxdb-...
166
257
  # Detect and configure every supported Agent already used on this host.
167
258
  ctxdb setup --all --api-key ctxdb-...
168
259
 
169
- # --base-url defaults to https://context-database.aliyuncs.com (public prod).
260
+ # --base-url defaults to https://api.cn-hangzhou.agentcontext.aliyuncs.com (public prod).
170
261
  # Pass --base-url <host> only if you target a different deployment
171
262
  # (e.g., a pre / staging host, or a self-hosted instance).
172
263
  # --user-id defaults to "default". Pass --user-id <bucket> only if you
@@ -281,12 +372,15 @@ For **hermes**, `ctxdb setup --agent hermes` writes two shell hooks under `~/.he
281
372
 
282
373
  `ctxdb` ships grouped non-interactive commands:
283
374
 
284
- - **Top-level**: `setup` / `status` / `ping` / `debug` / `uninstall` / `update` (`upgrade` alias)
375
+ - **Top-level**: `setup` / `status` / `ping` / `debug` / `uninstall` / `upgrade` (`update` alias)
285
376
  - **Memory**: `memory add|search|list|get|update|delete`, plus the `memory promotion` subgroup (记忆成文): `memory promotion generate|list|get|approve|reject|batch-action|batch-delete|resolve-doubts` and the `memory promotion template list|create|get|update|delete|set-default|clear-default` / `memory promotion settings get|update` sub-subgroups
286
- - **KB**: `kb upload-text|upload-file|update-text|update-file|list|documents-list|document-get|search`, plus the `kb review` subgroup: `kb review list|get|action|resolve-conflicts|batch-action|batch-delete|delete`, `kb review template list|create|update|delete|get|set-default|clear-default`, `kb review settings get|update`
377
+ - **KB**: `kb create|upload-text|upload-file|update-text|update-file|list|documents-list|document-get|search|entities|entity-get|entity-chunks|relations`, plus the `kb review` subgroup: `kb review list|get|action|resolve-conflicts|batch-action|batch-delete|delete`, `kb review template list|create|update|delete|get|set-default|clear-default`, `kb review settings get|update`
287
378
 
288
-
289
- See `ctxdb --help`.
379
+ Help is progressive: `ctxdb --help` lists command domains, group help such as
380
+ `ctxdb kb --help` lists direct subcommands, and a leaf such as
381
+ `ctxdb kb search --help` provides its complete arguments, constraints, output
382
+ modes, and examples. Agents can use `ctxdb help --all` for a bounded command
383
+ index or `ctxdb help kb search --json` for versioned structured discovery.
290
384
 
291
385
  ### Debug control and recall replay
292
386
 
@@ -305,7 +399,8 @@ Agent resolution follows the rest of the CLI: explicit `--agent`, then
305
399
  only `agents.<name>.debug`, makes no network request, and does not reinstall
306
400
  hooks, plugins, or skills. It requires that profile to already exist.
307
401
 
308
- The only official-production URL currently allowlisted is exactly
402
+ The official-production URL allowlist contains
403
+ `https://api.cn-hangzhou.agentcontext.aliyuncs.com` and the legacy
309
404
  `https://context-database.aliyuncs.com` (a trailing slash is equivalent).
310
405
  Policy is evaluated after profile/default inheritance and `CTXDB_BASE_URL`.
311
406
  Any other complete URL—including pre-production domains, numeric IPs,
@@ -342,6 +437,14 @@ fact-extraction). Use it when the user explicitly asks for a verbatim
342
437
  memory ("记住 / 请记忆 / 原文记下"); without `--no-infer` the server may
343
438
  rewrite, merge, or skip details.
344
439
 
440
+ `memory add [<text>] --image=<local-path>` adds an image-backed memory.
441
+ Repeat `--image` to attach multiple PNG, JPEG, or WebP files; text is optional
442
+ when at least one image is present. Image requests require inference, so they
443
+ cannot be combined with `--no-infer`. The command prints the server's
444
+ `PENDING` response and `event_id` immediately and does not poll for completion.
445
+ Recall remains text-based because the service converts image observations into
446
+ text facts.
447
+
345
448
  ### Memory promotion (记忆成文)
346
449
 
347
450
  The promotion commands live under the Memory group (`ctxdb memory promotion ...`) and cover the server's memory promotion pipeline: turn
@@ -349,7 +452,7 @@ accumulated memories into reviewed knowledge-base documents.
349
452
 
350
453
  ```sh
351
454
  # Task lifecycle
352
- ctxdb memory promotion generate "<topic>" [--knowledge-base-id=<kb-id>]
455
+ ctxdb memory promotion generate "<topic>" [--knowledge-base-id=<kb-id>] [--wait|--no-wait]
353
456
  ctxdb memory promotion list [--status=pending_review] [--page=N] [--page-size=N] \
354
457
  [--sort-by=quality_score] [--sort-order=asc|desc]
355
458
  ctxdb memory promotion get <promotion-id>
@@ -399,6 +502,42 @@ Notes:
399
502
 
400
503
  ### KB create/update completion mode
401
504
 
505
+ Knowledge-base lifecycle commands use the same Data API credential:
506
+
507
+ ```sh
508
+ ctxdb kb create <kb-name> [--description=<desc>] [--graph-enabled|--no-graph-enabled] [--review-enabled|--no-review-enabled]
509
+ ctxdb kb get (--id=<kb-id> | --name=<kb-name>)
510
+ ctxdb kb update <kb-id> [--name=<new-name>] [--description=<desc>] [--graph-enabled|--no-graph-enabled] [--review-enabled|--no-review-enabled]
511
+ ctxdb kb delete (--id=<kb-id> | --name=<kb-name>)
512
+ ```
513
+
514
+ `ctxdb kb list` defaults to the compact management fields needed to identify,
515
+ sort, and inspect each knowledge base. Pass `--raw` only when the complete
516
+ server rows, including large configuration and entity fields, are required.
517
+
518
+ `get` and `delete` require exactly one locator. `update` requires the canonical
519
+ knowledge-base ID and at least one mutable field.
520
+
521
+ Knowledge-base permissions use the same DATA API credential and server-side
522
+ authorization. Resolve a KB name with `kb get --name=...`, then use its ID:
523
+
524
+ ```sh
525
+ ctxdb kb acl subjects <kb-id> [--principal-type=member|group] [--principal-status=active|disabled] [--page=N] [--page-size=N] --json
526
+ ctxdb kb acl list <kb-id> [--principal-type=member|group] [--principal-id=<id>] [--permission=read|write|kb_manage] [--page=N] [--page-size=N] --json
527
+ ctxdb kb acl set <kb-id> --principal-type=member --principal-id=<member-id> --permission=read --json
528
+ ctxdb kb acl delete <acl-id> --json
529
+ ```
530
+
531
+ `subjects` retains the API's effective permission, source, direct grant, and
532
+ available-action fields; `list` returns explicit ACL grants. Both retain pagination
533
+ metadata (default page 1, page size 100). Page through the returned total for a
534
+ complete result. `set` changes one direct grant; members accept `read`, `write`,
535
+ or `kb_manage`, while groups accept only `read` or `write`. `delete` removes only
536
+ the specified ACL ID, so inherited access may remain; read `subjects` again to
537
+ verify the effective result. All commands accept `--raw` for the original envelope.
538
+ Writes require advanced permission mode and appropriate server-side authority;
539
+ the CLI propagates a refusal without enabling the mode or using another identity.
540
+
402
541
  `kb upload-text`, `kb upload-file`, `kb update-text`, and `kb update-file`
403
542
  return as soon as the service accepts the document. The returned document may still have
404
543
  `ingest_status: "processing"`; acceptance does not mean ingestion succeeded.
@@ -408,6 +547,14 @@ return as soon as the service accepts the document. The returned document may st
408
547
  - Existing `--no-wait` calls remain valid and behave like the new default.
409
548
  - `--wait` and `--no-wait` cannot be combined.
410
549
 
550
+ With `--wait`, the CLI writes one `document_accepted` JSON receipt to stderr
551
+ before polling, containing the returned `document_id`, `knowledge_base_id` (when
552
+ available), and `ingest_status`. This is acceptance, not proof of completed
553
+ ingestion. Keep stderr separate when parsing the final stdout JSON. If the wait
554
+ is interrupted, query the receipt's ID and current logical document before
555
+ deciding whether another write is necessary; an older ID may still expose an
556
+ older version's chunks. The receipt contains no document body or credentials.
557
+
411
558
  Scripts that relied on implicit terminal polling must migrate to:
412
559
 
413
560
  ```sh
@@ -447,6 +594,61 @@ Every successful update returns the canonical `document.id` and
447
594
  same-content updates may reuse it. Callers must retain the returned ID for the
448
595
  next update; `--wait` also polls the returned ID/KB pair rather than caller input.
449
596
 
597
+ ### Knowledge graph read commands
598
+
599
+ `kb entities` / `kb entity-get` / `kb entity-chunks` / `kb relations` cover the
600
+ four knowledge-graph read DATA APIs (`GET /v1/knowledge/entities`,
601
+ `/v1/knowledge/entities/detail`, `/v1/knowledge/entities/chunks`,
602
+ `/v1/knowledge/entity-relations`). They give agents real entity navigation
603
+ instead of re-querying `kb search` with rewritten keywords. Every command
604
+ accepts `--agent` (`CTXDB_AGENT`) and `--json`, and follows the three-tier
605
+ projection (`kb search` discipline): default prints a minimal agent view,
606
+ `--verbose` adds provenance/alias fields, `--raw` ships the server response
607
+ verbatim (Box envelope included for `entity-get`). Value validation (mode
608
+ enum, page-size clamps, the 20-id cap, the limit range) belongs to the
609
+ kernel — its 400s are surfaced, never swallowed or preempted; missing
610
+ required flags or malformed integers print usage and exit 2 before any
611
+ request is sent.
612
+
613
+ ```sh
614
+ # List / search entities. No keyword = paginated list; keyword enters name
615
+ # search and --mode picks the matching rule (exact | fuzzy | semantic).
616
+ ctxdb kb entities [--kb=<kb-id>] [--page=N] [--page-size=N]
617
+ ctxdb kb entities "graph rag" --kb=<kb-id> --mode=semantic
618
+
619
+ # Single entity detail — both locators required; full untruncated
620
+ # source_document_ids + aliases.
621
+ ctxdb kb entity-get --kb=<kb-id> --entity-id=<id>
622
+
623
+ # Source-chunk evidence behind up to 20 entities (limit 1..200, default 20).
624
+ ctxdb kb entity-chunks --kb=<kb-id> --entity-ids=<id1>,<id2> [--limit=N]
625
+
626
+ # Relations. The two entity filters are NOT aliases:
627
+ # --entity-id=X → 1-hop expansion, EITHER endpoint matches X
628
+ # --entity-ids=A,B → induced subgraph, BOTH endpoints must be in the set
629
+ ctxdb kb relations --kb=<kb-id> --entity-id=<id>
630
+ ctxdb kb relations --kb=<kb-id> --entity-ids=<a>,<b> [--relation-type=<t>] \
631
+ [--page=N] [--page-size=N] [--max-nodes=N] [--max-edges=N]
632
+ ```
633
+
634
+ Output semantics worth knowing:
635
+
636
+ - List responses (`entities` / `relations`) carry `total` + `page` +
637
+ `page_size`; there is no `truncated` flag on these endpoints.
638
+ - Under `--mode=semantic`, `total` is the size of the bounded candidate pool,
639
+ **not** the full match count.
640
+ - In entity list items, `source_document_ids` is truncated (20 max) —
641
+ `source_document_count` is the truth; fetch `entity-get` for full
642
+ provenance.
643
+ - `entity-chunks` carries `total`, `candidate_total` and `truncated` so you
644
+ can tell "that's all the evidence" from "the limit budget ran out".
645
+ Entities that don't exist or have no provenance are silently skipped —
646
+ partial hits are normal batch behavior.
647
+ - `relations --verbose` adds `nodes[]`: the hydrated endpoint entities with
648
+ their `(knowledge_base_id, entity_id)` locator pairs. `nodes` may be
649
+ incomplete by design (deleted endpoints are omitted); relation items always
650
+ keep denormalized endpoint names.
651
+
450
652
  ### Knowledge review commands
451
653
 
452
654
  `kb review` covers the Knowledge Review DATA APIs: review-queue handling
@@ -567,7 +769,7 @@ Lives at `~/.ctxdb/ctxdb.json` (co-located with logs at `~/.ctxdb/logs/`). Schem
567
769
  "agents": {
568
770
  "qoder": {
569
771
  "api_key": "ctxdb-...",
570
- "base_url": "https://context-database.aliyuncs.com",
772
+ "base_url": "https://api.cn-hangzhou.agentcontext.aliyuncs.com",
571
773
  "user_id": "default",
572
774
  "auto_capture": true,
573
775
  "auto_recall": true,
@@ -607,7 +809,7 @@ Field reference:
607
809
 
608
810
  Env-var overrides apply to the selected agent config (env wins): `CTXDB_AGENT` / `CTXDB_ACCESS_TOKEN` / `CTXDB_API_KEY` / `CTXDB_BASE_URL` / `CTXDB_USER_ID` / `CTXDB_AGENT_ID` / `CTXDB_APP_ID`. The internal login command additionally reads `CTXDB_LOGIN_SERVER` as its provider-neutral login endpoint. The last two default to unset — the request body omits `agent_id`/`app_id` entirely; set them only when you want per-agent / per-app scope isolation on the server.
609
811
 
610
- Downstream Agent hosts can set `CTXDB_ACCESS_TOKEN` to send `Authorization: Bearer <token>` to the Data API. It is runtime-only, never written to `~/.ctxdb/ctxdb.json`, and takes precedence over an API key for CLI, process hooks, and the in-process OpenCode plugin; a rejected token does not fall back to the API key. `ctxdb setup` remains API-key-only and never persists or validates an access token.
812
+ Downstream Agent hosts can set `CTXDB_ACCESS_TOKEN` to send `Authorization: Bearer <token>` to the Data API. It is runtime-only, never written to `~/.ctxdb/ctxdb.json`, and takes precedence over a managed session or API key for CLI, process hooks, and OpenCode; a rejected token does not fall back to another credential. `ctxdb setup` can use a managed reference or an environment AT for validation, but never persists the AT. An environment-only credential must remain available to the Agent runtime after setup.
611
813
 
612
814
  Hook/plugin escape hatch: set `CTXDB_SKIP_HOOKS=TRUE` on the agent process to make all ctxdb hook entrypoints exit immediately before reading config or calling the API. Direct `ctxdb memory` / `ctxdb kb` / `ctxdb setup` CLI commands are unchanged.
613
815
 
@@ -702,3 +904,7 @@ Maintainer-facing docs (source layout, dev/test workflows, server-config archive
702
904
  ## License
703
905
 
704
906
  Apache-2.0
907
+
908
+ 上传时可用 `ctxdb kb upload-text` 或 `ctxdb kb upload-file` 的 `--review-enabled` / `--no-review-enabled` 覆盖本次文档评审开关;不传时沿用服务端默认,不修改知识库策略。两标志互斥,分片上传保留同一选择。上传回执不代表评审或入库完成,应查询实际状态。
909
+
910
+ `memory get <fact-id> --verbose` 通过原生 Fact 详情接口读取状态、关联实体 ID、来源及参考/记录时间;默认 `memory get` 的 mem0 输出保持兼容。召回统计可从同一身份的 `memory list` 中按 ID 对应读取。