@aliyunrds/ctxdb 0.0.1

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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [2023] [Taranjeet Singh]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,202 @@
1
+ # @aliyunrds/ctxdb
2
+
3
+ Unified access layer for RDS ContextDatabase. One `ctxdb` CLI (memory + KB ops), one `setup --agent <…>` installer, per-agent SKILL.md — supports multiple code agents from a single package.
4
+
5
+ | Agent | Hooks | Skill install path | Skill style |
6
+ |---|---|---|---|
7
+ | **qoder** | ✅ UserPromptSubmit + Stop + SessionStart | `~/.qoder/skills/ctxdb/` | hooks-driven (auto capture/recall) |
8
+ | **codex** | ✅ UserPromptSubmit + Stop + SessionStart | `~/.codex/skills/ctxdb/` | hooks-driven (auto capture/recall) |
9
+ | **claude** | ✅ UserPromptSubmit + Stop + SessionStart | `~/.claude/skills/ctxdb/` | hooks-driven (auto capture/recall) |
10
+
11
+ Config and logs live under `~/.ctxdb/`. `~/.ctxdb/ctxdb.json` is one file, but runtime config is isolated per agent under `agents.qoder`, `agents.codex`, and `agents.claude`. (Pre-2026-05-23 installs used `~/.ctxdb.json` at the home root; running `ctxdb setup --agent <name>` migrates the file into the selected agent section.)
12
+
13
+ ## Install
14
+
15
+ ```sh
16
+ npm install -g @aliyunrds/ctxdb
17
+
18
+ # Qoder (hooks + skill)
19
+ ctxdb setup --agent qoder --api-key ctxdb-...
20
+ # Codex (hooks + skill)
21
+ ctxdb setup --agent codex --api-key ctxdb-...
22
+ # Claude Code (hooks + skill)
23
+ ctxdb setup --agent claude --api-key ctxdb-...
24
+
25
+ # --base-url defaults to https://context-database.aliyuncs.com (public prod).
26
+ # Pass --base-url <host> only if you target a different deployment
27
+ # (e.g., a pre / staging host, or a self-hosted instance).
28
+ # --user-id defaults to "default". Pass --user-id <bucket> only if you
29
+ # need to isolate this install from another access layer or machine
30
+ # sharing the same workspace (see "Configuration" below).
31
+
32
+ # Verify
33
+ ctxdb status --json
34
+ ```
35
+
36
+ Setup first checks that the target agent home exists (`~/.qoder`, `~/.codex`, or `~/.claude`). If the directory is missing, install or start that agent once before running `ctxdb setup --agent <name>`.
37
+
38
+ For **qoder**, **codex**, and **claude**, restart the harness (CLI: just exit + restart; app: Cmd+R or quit/relaunch) so it picks up the new hooks/skill. For **codex**, setup also writes `[features].hooks = true` into `~/.codex/config.toml` (creating the file if missing) — Codex won't fire any hook entries without it. On first use Codex may prompt you to trust the new hook commands.
39
+
40
+ ## What it does
41
+
42
+ For **qoder**, **codex**, and **claude**, hooks fire automatically:
43
+
44
+ | Trigger | Hook | What runs |
45
+ |---|---|---|
46
+ | Session starts | `SessionStart` | Build a short cwd/git-signal query, recall relevant memories, and inject warm-up context as `additionalContext` |
47
+ | User submits a prompt | `UserPromptSubmit` | Search `/v3/memories/search/`, format a `<recalled-memories>` block, inject as additional context. **By default only memory is recalled.** Set `recall_knowledge: true` in the selected agent config to also pull KB chunks into a `<external-knowledge>` block; otherwise the recommended path for KB is the agent calling `ctxdb kb search --agent <name>` explicitly when the user asks (see SKILL.md) |
48
+ | Agent finishes its turn | `Stop` | Read transcript, detect KB-upload turns and skip capture (so uploaded content doesn't bleed into long-term memory), slice the current turn, sanitize the input, POST to memory store |
49
+
50
+ Implementation note: qoder/Claude consume the JSON `hookSpecificOutput.additionalContext` shape; Codex has been verified on this machine through `~/.codex/hooks.json`, `[features].hooks = true`, and hook audit logs, where non-empty stdout from `UserPromptSubmit`/`SessionStart` is treated as injected context. The same hook core is shared; setup passes `--agent=<name>` so each hook reads its own config section.
51
+
52
+ ## CLI
53
+
54
+ `ctxdb` ships 19 subcommands:
55
+
56
+ - **Top-level**: `init` / `status` / `ping` / `setup` / `teardown`
57
+ - **Memory**: `memory add|search|list|get|update|delete`
58
+ - **KB**: `kb upload-text|upload-file|list|documents-list|document-get|search`
59
+
60
+ See `ctxdb --help`.
61
+
62
+ `setup` mandates `--agent <qoder|codex|claude>` because it mutates that agent's hooks/skills. Memory and KB commands also accept `--agent <name>` so agents use their own config section; when omitted, `CTXDB_AGENT` wins, otherwise `qoder` is used for backward compatibility. `teardown` loops every supported agent.
63
+
64
+ `memory add … --no-infer` stores the text verbatim (skips server-side LLM
65
+ fact-extraction). Use it when the user explicitly asks for a verbatim
66
+ memory ("记住 / 请记忆 / 原文记下"); without `--no-infer` the server may
67
+ rewrite, merge, or skip details.
68
+
69
+ `kb search <query> [--kb=name1,name2] [--top-k=N] [--threshold=F]` is the
70
+ agent-driven KB recall path — calls `POST /v1/knowledge/query` directly
71
+ (distinct from `memory search --knowledge`, which is a memory + KB hybrid
72
+ search). The SKILL points the agent here when the user explicitly asks for
73
+ KB lookup ("结合知识库查询" / "从知识库召回"). `--kb` is comma-separated;
74
+ omit it to search across all KBs.
75
+
76
+ ## Configuration
77
+
78
+ Lives at `~/.ctxdb/ctxdb.json` (co-located with logs at `~/.ctxdb/logs/`). Schema:
79
+
80
+ ```json
81
+ {
82
+ "version": 2,
83
+ "agents": {
84
+ "qoder": {
85
+ "api_key": "ctxdb-...",
86
+ "base_url": "https://context-database.aliyuncs.com",
87
+ "user_id": "default",
88
+ "auto_capture": true,
89
+ "auto_recall": true,
90
+ "warmup_recall": true,
91
+ "recall_knowledge": false,
92
+ "top_k": 5,
93
+ "threshold": 0.4,
94
+ "knowledge_top_k": 6,
95
+ "debug": false
96
+ },
97
+ "codex": { "...": "same schema, independent values" },
98
+ "claude": { "...": "same schema, independent values" }
99
+ }
100
+ }
101
+ ```
102
+
103
+ Agent selection is driven by `--agent <qoder|codex|claude>` on every CLI invocation, falling back to `CTXDB_AGENT` env, then to `qoder`. There is no `default_agent` field — older installs that have one written get it dropped on the next save.
104
+
105
+ Field reference:
106
+
107
+ | Key | Type | Default | Meaning |
108
+ |---|---|---|---|
109
+ | `user_id` | str | `"default"` | mem0-layer bucket key on every capture/recall call. The server's tenant isolation runs on `member_id` (injected from `X-API-Key`), so this is an optional per-user/agent slice. Override with `ctxdb setup --agent <a> --user-id <bucket>` or `CTXDB_USER_ID=<bucket>` when you need to isolate this install from another access layer or machine sharing the same workspace |
110
+ | `auto_capture` | bool | `true` | Stop hook captures each turn into long-term memory for the selected agent |
111
+ | `auto_recall` | bool | `true` | UserPromptSubmit hook recalls memory on each user prompt for the selected agent |
112
+ | `warmup_recall` | bool | `true` | SessionStart hook recalls cwd/git-related memories for the selected agent |
113
+ | `recall_knowledge` | bool | `false` | When `auto_recall` is on, also pull KB chunks alongside memory. Default is **off** — the recommended KB-recall path is the agent calling `kb search --agent <name>` explicitly when the user asks |
114
+ | `top_k` / `threshold` | int / float | `5` / `0.4` | Memory recall pagination + similarity floor. `5` keeps the codex TUI `hook context: ...` line short enough to scan and bounds token spend on the modal recall path; raise it per-agent if you want more candidates |
115
+ | `knowledge_top_k` | int | `6` | KB chunks pulled per recall (only effective when `recall_knowledge: true`) |
116
+ | `debug` | bool | `false` | Verbose hook logging (`~/.ctxdb/logs/ctxdb.log`) |
117
+
118
+ Env-var overrides apply to the selected agent config (env wins): `CTXDB_AGENT` / `CTXDB_API_KEY` / `CTXDB_BASE_URL` / `CTXDB_USER_ID`.
119
+
120
+ ## Architecture
121
+
122
+ ```
123
+ @aliyunrds/ctxdb ← this package (CLI + setup + hooks + skills)
124
+
125
+ └─ depends on @aliyunrds/ctxdb-shared ← input sanitation,
126
+ prompt-injection defenses,
127
+ memory/KB types, recall pipeline
128
+ (also consumed by openclaw_memory_rds_ctxdb)
129
+ ```
130
+
131
+ Two npm packages total. `@aliyunrds/ctxdb-shared` stays separate because OpenClaw's plugin fork also depends on it; this package owns everything user-facing (CLI bin, installer, per-agent skills, hooks).
132
+
133
+ ## Uninstall
134
+
135
+ > ⚠️ **Order matters.** npm 7+ removed the `preuninstall` / `postuninstall` lifecycle hooks — `npm uninstall -g` does **not** run any cleanup we ship. If you `npm uninstall` first you'll leave agent hook entries pointing at a now-missing binary, plus orphaned skills and `~/.ctxdb/` state. Always run **`ctxdb teardown` first, then `npm uninstall -g`**.
136
+
137
+ ### Full removal (recommended)
138
+
139
+ ```sh
140
+ # 1. Strip hooks + skills + (optionally) config + logs while the binary still works.
141
+ ctxdb teardown --purge-all # everything: hooks, skills, ~/.ctxdb/ctxdb.json, ~/.ctxdb/logs/
142
+
143
+ # 2. Then drop the npm binaries.
144
+ npm uninstall -g @aliyunrds/ctxdb @aliyunrds/ctxdb-shared
145
+ ```
146
+
147
+ After step 1, `ctxdb teardown` prints the exact `npm uninstall` command to run next — copy it from your terminal.
148
+
149
+ ### Partial removal
150
+
151
+ ```sh
152
+ # Per-agent only — unwires hooks, removes ~/.<agent>/skills/ctxdb, AND
153
+ # deletes agents.<X> from ~/.ctxdb/ctxdb.json. Other agents' sections are
154
+ # preserved verbatim. If <X> was the last configured agent, ~/.ctxdb/ctxdb.json
155
+ # itself is unlinked so a future `ctxdb setup --agent <X>` runs through the
156
+ # first-time install path cleanly.
157
+ ctxdb setup --remove --agent qoder
158
+ ctxdb setup --remove --agent codex
159
+ ctxdb setup --remove --agent claude
160
+
161
+ # Wholesale across all agents, but keep config + logs for re-setup later:
162
+ ctxdb teardown # all agents, keeps ~/.ctxdb/{ctxdb.json,logs/}
163
+ ctxdb teardown --purge-config # also deletes ~/.ctxdb/ctxdb.json
164
+ ctxdb teardown --purge-logs # also deletes ~/.ctxdb/logs/
165
+ ```
166
+
167
+ ### What teardown does (and doesn't) touch
168
+
169
+ - **Hook entries in `~/.qoder/settings.json`, `~/.codex/hooks.json`, and `~/.claude/settings.json`**: stripped precisely by marker (`_ctxdb = @aliyunrds/ctxdb`, plus legacy keys `_ctxdbQoder` / `_ctxdbPackage` and the legacy `@aliyunrds/ctxdb-qoder` value for installs predating the unified marker). Any hooks you added yourself stay. A timestamped `*.bak-ctxdb-<TS>` is written before each modification (rotation keeps the 5 most recent).
170
+ - **Skill directories**: `~/.<agent>/skills/ctxdb/` for each set-up agent, plus legacy dirs (`ctxdb-qoder`, `rds-ctxdb-qoder`, `qoder-ctxdb`) under `~/.qoder/skills/` from older package names.
171
+ - **`~/.ctxdb/` state**: only with `--purge-config` / `--purge-logs` / `--purge-all`. Defensive: `--purge-all` removes the `~/.ctxdb/` root only if it's empty after the named files are deleted (won't blanket-rm an unknown directory).
172
+ - **`~/.codex/config.toml` `[features].hooks`**: **NOT** reverted. Setup adds `hooks = true` so Codex will fire ctxdb's hook entries; teardown leaves the flag alone because (a) the user may have wanted it on for non-ctxdb hooks, and (b) it's harmless when `~/.codex/hooks.json` is empty. If you want it off, edit the file by hand.
173
+ - **`npm` itself**: never. `ctxdb teardown` does not call your host package manager — that's the second command above.
174
+
175
+ ## Remote SSH (Qoder IDE)
176
+
177
+ When you connect to a remote host via Qoder IDE's SSH session, `ctxdb` does **not** travel with the Qoder server. Qoder syncs its own server bits to the remote machine, but `~/.qoder/{settings.json, skills/}` and `~/.ctxdb/ctxdb.json` are per-host — your local hooks, config, and skill are not propagated.
178
+
179
+ To enable autoCapture / autoRecall in the remote session, run the same install on the remote machine:
180
+
181
+ ```sh
182
+ # on the remote host
183
+ npm install -g @aliyunrds/ctxdb
184
+ ctxdb setup --agent qoder --api-key ctxdb-...
185
+ # Both --base-url and --user-id are optional; they default to the public
186
+ # prod host and the "default" bucket respectively. Override either when
187
+ # you target a non-prod deployment or want per-host bucket isolation.
188
+ ```
189
+
190
+ Each remote host needs its own one-time setup. Omitting `--user-id` lands every host on the shared `"default"` bucket, so memory flows freely across machines that share an API key. Pass a distinct `--user-id` per host when you want per-host bucketing.
191
+
192
+ ## Lightweight (no-node) alternative
193
+
194
+ `SKILL-one-in-all.md` is a single-file bash-only skill: zero install, no node runtime, but no hooks and no streaming/upload helpers. Use it when you can't or don't want to ship the npm package; use this package when you want hooks (qoder/codex/claude) or a richer CLI surface.
195
+
196
+ ## Developer docs
197
+
198
+ Maintainer-facing docs (source layout, dev/test workflows, server-config archives) live in the project's internal notebooks and are not packaged with this release. npm consumers can ignore this section.
199
+
200
+ ## License
201
+
202
+ Apache-2.0
@@ -0,0 +1,136 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ CtxdbError
4
+ } from "./chunk-L4YJ7LDI.js";
5
+
6
+ // src/lib/recall-orchestrator.ts
7
+ import {
8
+ buildExternalKnowledgeBlock
9
+ } from "@aliyunrds/ctxdb-shared";
10
+
11
+ // src/lib/format-recall.ts
12
+ import {
13
+ formatRecalledMemoriesBlock
14
+ } from "@aliyunrds/ctxdb-shared";
15
+ var OPEN_TAG = "<recalled-memories>";
16
+ var CLOSE_TAG = "</recalled-memories>";
17
+ var TIME_ANCHOR_RE = /^\[Time anchor:[^\]]*\]\s*/;
18
+ var IMPORTANCE_SUFFIX_RE = /\s*\(\d+%\)\s*$/;
19
+ var CATEGORY_LABEL_RE = /^[A-Z][A-Za-z0-9_-]*:$/;
20
+ function slimRecalledMemoriesBlock(memories, userId) {
21
+ const raw = formatRecalledMemoriesBlock(memories, userId);
22
+ if (!raw.includes("Stored memories for ")) {
23
+ return raw;
24
+ }
25
+ return slimRewrite(raw, userId);
26
+ }
27
+ function slimRewrite(raw, userId) {
28
+ const lines = raw.split("\n");
29
+ const isBullet = (l) => l.startsWith("- ");
30
+ const isCategory = (l) => CATEGORY_LABEL_RE.test(l) && !l.startsWith("Stored");
31
+ let bulletCount = 0;
32
+ let categoryCount = 0;
33
+ for (const l of lines) {
34
+ if (isBullet(l)) bulletCount++;
35
+ else if (isCategory(l)) categoryCount++;
36
+ }
37
+ const dropCategoryLabels = categoryCount <= 1;
38
+ const out = [];
39
+ for (let i = 0; i < lines.length; i++) {
40
+ const line = lines[i];
41
+ if (line === OPEN_TAG || line === CLOSE_TAG) {
42
+ out.push(line);
43
+ continue;
44
+ }
45
+ if (line.startsWith("Stored memories for ")) {
46
+ out.push(`Recalled ${bulletCount} memories for "${userId}":`);
47
+ continue;
48
+ }
49
+ if (line === "") continue;
50
+ if (dropCategoryLabels && isCategory(line)) continue;
51
+ if (isBullet(line)) {
52
+ let body = line.slice(2);
53
+ body = body.replace(TIME_ANCHOR_RE, "");
54
+ body = body.replace(IMPORTANCE_SUFFIX_RE, "");
55
+ let j = i + 1;
56
+ const continuations = [];
57
+ while (j < lines.length) {
58
+ const next = lines[j];
59
+ if (isBullet(next) || isCategory(next) || next === "" || next === CLOSE_TAG)
60
+ break;
61
+ continuations.push(next);
62
+ j++;
63
+ }
64
+ if (continuations.length > 0) {
65
+ body = body + " " + continuations.join(" ");
66
+ }
67
+ i = j - 1;
68
+ body = body.replace(IMPORTANCE_SUFFIX_RE, "");
69
+ body = body.replace(/\s+/g, " ").trim();
70
+ if (body) out.push(`\xB7 ${body} `);
71
+ continue;
72
+ }
73
+ out.push(line);
74
+ }
75
+ return out.join("\n");
76
+ }
77
+
78
+ // src/lib/recall-orchestrator.ts
79
+ var EMPTY = {
80
+ ok: false,
81
+ reason: "",
82
+ additionalContext: "",
83
+ memoryCount: 0,
84
+ knowledgeChunkCount: 0
85
+ };
86
+ async function recallTurn(prompt, cfg, client) {
87
+ if (!prompt.trim()) return { ...EMPTY, reason: "empty_prompt" };
88
+ if (!cfg.apiKey || !cfg.baseUrl) {
89
+ return { ...EMPTY, reason: "config_incomplete" };
90
+ }
91
+ if (!cfg.autoRecall) return { ...EMPTY, reason: "auto_recall_disabled" };
92
+ const body = {
93
+ query: prompt,
94
+ user_id: cfg.userId,
95
+ top_k: cfg.topK,
96
+ threshold: cfg.threshold
97
+ };
98
+ if (cfg.recallKnowledge) {
99
+ body.knowledge = { enable: true, top_k: cfg.knowledgeTopK };
100
+ }
101
+ let resp;
102
+ try {
103
+ resp = await client.postJson("/v3/memories/search/", body);
104
+ } catch (err) {
105
+ const msg = err instanceof CtxdbError ? err.message : String(err);
106
+ return { ...EMPTY, reason: `http_error: ${msg}` };
107
+ }
108
+ if (!resp || typeof resp !== "object") {
109
+ return { ...EMPTY, reason: "bad_response_shape" };
110
+ }
111
+ const r = resp;
112
+ const memories = Array.isArray(r.results) ? r.results : Array.isArray(r.memories) ? r.memories : [];
113
+ const knowledge = r.knowledge && typeof r.knowledge === "object" ? r.knowledge : null;
114
+ const chunks = Array.isArray(knowledge?.chunks) ? knowledge.chunks : [];
115
+ const blocks = [];
116
+ if (memories.length > 0) {
117
+ blocks.push(slimRecalledMemoriesBlock(memories, cfg.userId));
118
+ }
119
+ if (chunks.length > 0) {
120
+ blocks.push(buildExternalKnowledgeBlock(chunks, cfg.userId));
121
+ }
122
+ if (blocks.length === 0) {
123
+ return { ...EMPTY, ok: true, reason: "nothing_to_inject" };
124
+ }
125
+ return {
126
+ ok: true,
127
+ reason: "ok",
128
+ additionalContext: blocks.join("\n\n"),
129
+ memoryCount: memories.length,
130
+ knowledgeChunkCount: chunks.length
131
+ };
132
+ }
133
+
134
+ export {
135
+ recallTurn
136
+ };
@@ -0,0 +1,35 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/lib/logger.ts
4
+ import { appendFileSync, mkdirSync } from "fs";
5
+ import { homedir } from "os";
6
+ import { dirname, join } from "path";
7
+ function logPath() {
8
+ return join(homedir(), ".ctxdb", "logs", "ctxdb.log");
9
+ }
10
+ var _enabled = null;
11
+ function setDebug(enabled) {
12
+ _enabled = enabled;
13
+ }
14
+ function debug(tag, msg, data) {
15
+ if (_enabled !== true) return;
16
+ const ts = (/* @__PURE__ */ new Date()).toISOString();
17
+ let line = `${ts} [${tag}] ${msg}`;
18
+ if (data !== void 0) {
19
+ const s = typeof data === "string" ? data : JSON.stringify(data, null, 2);
20
+ line += `
21
+ ${s}`;
22
+ }
23
+ line += "\n";
24
+ const p = logPath();
25
+ try {
26
+ mkdirSync(dirname(p), { recursive: true });
27
+ appendFileSync(p, line, "utf-8");
28
+ } catch {
29
+ }
30
+ }
31
+
32
+ export {
33
+ setDebug,
34
+ debug
35
+ };