@memtensor/memos-local-openclaw-plugin 1.0.4-beta.5 → 1.0.4-beta.7
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 +23 -23
- package/dist/capture/index.d.ts +1 -1
- package/dist/capture/index.d.ts.map +1 -1
- package/dist/capture/index.js +28 -2
- package/dist/capture/index.js.map +1 -1
- package/dist/client/connector.d.ts +1 -2
- package/dist/client/connector.d.ts.map +1 -1
- package/dist/client/connector.js +18 -19
- package/dist/client/connector.js.map +1 -1
- package/dist/client/hub.d.ts.map +1 -1
- package/dist/client/hub.js +22 -0
- package/dist/client/hub.js.map +1 -1
- package/dist/client/skill-sync.d.ts +7 -0
- package/dist/client/skill-sync.d.ts.map +1 -1
- package/dist/client/skill-sync.js +10 -0
- package/dist/client/skill-sync.js.map +1 -1
- package/dist/hub/server.d.ts.map +1 -1
- package/dist/hub/server.js +101 -81
- package/dist/hub/server.js.map +1 -1
- package/dist/hub/user-manager.d.ts +2 -0
- package/dist/hub/user-manager.d.ts.map +1 -1
- package/dist/hub/user-manager.js +5 -1
- package/dist/hub/user-manager.js.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -2
- package/dist/index.js.map +1 -1
- package/dist/storage/sqlite.d.ts +54 -20
- package/dist/storage/sqlite.d.ts.map +1 -1
- package/dist/storage/sqlite.js +185 -101
- package/dist/storage/sqlite.js.map +1 -1
- package/dist/tools/memory-search.d.ts +3 -1
- package/dist/tools/memory-search.d.ts.map +1 -1
- package/dist/tools/memory-search.js +3 -1
- package/dist/tools/memory-search.js.map +1 -1
- package/dist/viewer/html.d.ts.map +1 -1
- package/dist/viewer/html.js +1619 -629
- package/dist/viewer/html.js.map +1 -1
- package/dist/viewer/server.d.ts +14 -8
- package/dist/viewer/server.d.ts.map +1 -1
- package/dist/viewer/server.js +545 -141
- package/dist/viewer/server.js.map +1 -1
- package/index.ts +355 -41
- package/package.json +1 -1
- package/skill/memos-memory-guide/SKILL.md +64 -26
- package/src/capture/index.ts +29 -1
- package/src/client/connector.ts +15 -21
- package/src/client/hub.ts +18 -0
- package/src/client/skill-sync.ts +14 -0
- package/src/hub/server.ts +88 -74
- package/src/hub/user-manager.ts +7 -3
- package/src/index.ts +7 -2
- package/src/storage/sqlite.ts +192 -122
- package/src/tools/memory-search.ts +2 -1
- package/src/viewer/html.ts +1619 -629
- package/src/viewer/server.ts +506 -128
|
@@ -1,17 +1,22 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: memos-memory-guide
|
|
3
|
-
description: "Use the MemOS Local memory system to search and use the user's past conversations. Use this skill whenever the user refers to past chats, their own preferences or history, or when you need to answer from prior context. When auto-recall returns nothing (long or unclear user query), generate your own short search query and call memory_search. Available tools: memory_search, memory_get, memory_write_public, task_summary, skill_get, skill_search, skill_install, skill_publish, skill_unpublish, memory_timeline, memory_viewer."
|
|
3
|
+
description: "Use the MemOS Local memory system to search and use the user's past conversations. Use this skill whenever the user refers to past chats, their own preferences or history, or when you need to answer from prior context. When auto-recall returns nothing (long or unclear user query), generate your own short search query and call memory_search. Available tools: memory_search, memory_get, memory_write_public, memory_share, memory_unshare, task_summary, skill_get, skill_search, skill_install, skill_publish, skill_unpublish, network_memory_detail, network_skill_pull, network_team_info, memory_timeline, memory_viewer."
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# MemOS Local Memory — Agent Guide
|
|
7
7
|
|
|
8
|
-
This skill describes how to use the MemOS memory tools so you can reliably search and use the user's long-term conversation history, query
|
|
8
|
+
This skill describes how to use the MemOS memory tools so you can reliably search and use the user's long-term conversation history, query team-shared data, share tasks, and discover or pull reusable skills.
|
|
9
|
+
|
|
10
|
+
Two sharing planes exist and must not be confused:
|
|
11
|
+
|
|
12
|
+
- **Local agent sharing:** visible to agents in the same OpenClaw workspace only.
|
|
13
|
+
- **Team sharing:** visible to teammates through the configured team server.
|
|
9
14
|
|
|
10
15
|
## How memory is provided each turn
|
|
11
16
|
|
|
12
17
|
- **Automatic recall (hook):** At the start of each turn, the system runs a memory search using the user's current message and injects relevant past memories into your context. You do not need to call any tool for that.
|
|
13
18
|
- **When that is not enough:** If the user's message is very long, vague, or the automatic search returns **no memories**, you should **generate your own short, focused query** and call `memory_search` yourself.
|
|
14
|
-
- **Memory isolation:** Each agent can only see its own local private memories and local `public` memories.
|
|
19
|
+
- **Memory isolation:** Each agent can only see its own local private memories and local `public` memories. Team-shared data only appears when you search with `scope="group"` or `scope="all"`.
|
|
15
20
|
|
|
16
21
|
## Tools — what they do and when to call
|
|
17
22
|
|
|
@@ -24,9 +29,10 @@ This skill describes how to use the MemOS memory tools so you can reliably searc
|
|
|
24
29
|
- You need to search with a different angle (e.g. filter by `role='user'`).
|
|
25
30
|
- **Parameters:**
|
|
26
31
|
- `query` (string, **required**) — Natural language search query.
|
|
27
|
-
- `
|
|
28
|
-
- `
|
|
29
|
-
- `
|
|
32
|
+
- `scope` (string, optional) — `'local'` (default) for current agent + local shared memories, or `'group'` / `'all'` to include team-shared memories.
|
|
33
|
+
- `maxResults` (number, optional) — Increase when the first search is too narrow.
|
|
34
|
+
- `minScore` (number, optional) — Lower slightly if recall is too strict.
|
|
35
|
+
- `role` (string, optional) — Filter local results by `'user'`, `'assistant'`, `'tool'`, or `'system'`.
|
|
30
36
|
|
|
31
37
|
### memory_get
|
|
32
38
|
|
|
@@ -38,12 +44,32 @@ This skill describes how to use the MemOS memory tools so you can reliably searc
|
|
|
38
44
|
|
|
39
45
|
### memory_write_public
|
|
40
46
|
|
|
41
|
-
- **What it does:**
|
|
42
|
-
- **When to call:** In multi-agent or collaborative scenarios, when you
|
|
47
|
+
- **What it does:** Create a brand new local shared memory. These memories are visible to all agents in the same OpenClaw workspace during `memory_search`. This does **not** publish anything to the team server.
|
|
48
|
+
- **When to call:** In multi-agent or collaborative scenarios, when you want to create a new persistent shared note from scratch (e.g. shared decisions, conventions, configurations, workflows). Do not use it if you already have a specific memory chunk to expose.
|
|
43
49
|
- **Parameters:**
|
|
44
|
-
- `content` (string, **required**) — The content to write to
|
|
50
|
+
- `content` (string, **required**) — The content to write to local shared memory.
|
|
45
51
|
- `summary` (string, optional) — Short summary of the content.
|
|
46
52
|
|
|
53
|
+
### memory_share
|
|
54
|
+
|
|
55
|
+
- **What it does:** Share an existing memory either with local OpenClaw agents, to the team, or to both.
|
|
56
|
+
- **When to call:** You already have a useful memory chunk and want to expose it beyond the current agent.
|
|
57
|
+
- **Do not use when:** You are creating a new shared note from scratch. In that case use `memory_write_public`.
|
|
58
|
+
- **Parameters:**
|
|
59
|
+
- `chunkId` (string, **required**) — Existing memory chunk ID.
|
|
60
|
+
- `target` (string, optional) — `'agents'` (default), `'hub'`, or `'both'`.
|
|
61
|
+
- `visibility` (string, optional) — Team visibility when target includes team: `'public'` (default) or `'group'`.
|
|
62
|
+
- `groupId` (string, optional) — Optional team group ID when `visibility='group'`.
|
|
63
|
+
|
|
64
|
+
### memory_unshare
|
|
65
|
+
|
|
66
|
+
- **What it does:** Remove an existing memory from local agent sharing, team sharing, or both.
|
|
67
|
+
- **When to call:** A memory should no longer be visible outside the current agent or should be removed from the team.
|
|
68
|
+
- **Parameters:**
|
|
69
|
+
- `chunkId` (string, **required**) — Existing memory chunk ID.
|
|
70
|
+
- `target` (string, optional) — `'agents'`, `'hub'`, or `'all'` (default).
|
|
71
|
+
- `privateOwner` (string, optional) — Rare fallback only for older public memories that have no recorded original owner.
|
|
72
|
+
|
|
47
73
|
### task_summary
|
|
48
74
|
|
|
49
75
|
- **What it does:** Get the detailed summary of a complete task: title, status, narrative summary, and related skills. Use when `memory_search` returns a hit with a `task_id` and you need the full story. Preserves critical information: URLs, file paths, commands, error codes, step-by-step instructions.
|
|
@@ -62,11 +88,11 @@ This skill describes how to use the MemOS memory tools so you can reliably searc
|
|
|
62
88
|
|
|
63
89
|
### skill_search
|
|
64
90
|
|
|
65
|
-
- **What it does:** Search available skills by natural language. Searches your own skills,
|
|
91
|
+
- **What it does:** Search available skills by natural language. Searches your own skills, local shared skills, or both. It can also include team skills.
|
|
66
92
|
- **When to call:** The current task requires a capability or guide you don't have. Use `skill_search` to find one first; after finding it, use `skill_get` to read it, then `skill_install` to load it for future turns.
|
|
67
93
|
- **Parameters:**
|
|
68
94
|
- `query` (string, **required**) — Natural language description of the needed skill.
|
|
69
|
-
- `scope` (string, optional) —
|
|
95
|
+
- `scope` (string, optional) — `'mix'` (default, self + local shared), `'self'`, `'public'` (local shared only), or `'group'` / `'all'` to include team results.
|
|
70
96
|
|
|
71
97
|
### skill_install
|
|
72
98
|
|
|
@@ -77,40 +103,46 @@ This skill describes how to use the MemOS memory tools so you can reliably searc
|
|
|
77
103
|
|
|
78
104
|
### skill_publish
|
|
79
105
|
|
|
80
|
-
- **What it does:**
|
|
81
|
-
- **When to call:** You have a useful skill that other agents could benefit from
|
|
106
|
+
- **What it does:** Share a skill with local agents, or publish it to the team.
|
|
107
|
+
- **When to call:** You have a useful skill that other agents or your team could benefit from.
|
|
82
108
|
- **Parameters:**
|
|
83
109
|
- `skillId` (string, **required**) — The skill ID to publish.
|
|
110
|
+
- `target` (string, optional) — `'agents'` (default) or `'hub'`.
|
|
111
|
+
- `visibility` (string, optional) — When `target='hub'`, use `'public'` (default) or `'group'`.
|
|
112
|
+
- `groupId` (string, optional) — Optional team group ID when `target='hub'` and `visibility='group'`.
|
|
113
|
+
- `scope` (string, optional) — Backward-compatible alias for old calls. Prefer `target` + `visibility` in new calls.
|
|
84
114
|
|
|
85
115
|
### skill_unpublish
|
|
86
116
|
|
|
87
|
-
- **What it does:**
|
|
117
|
+
- **What it does:** Stop local agent sharing, remove a team-published copy, or do both.
|
|
88
118
|
- **When to call:** You want to stop sharing a previously published skill.
|
|
89
119
|
- **Parameters:**
|
|
90
120
|
- `skillId` (string, **required**) — The skill ID to unpublish.
|
|
121
|
+
- `target` (string, optional) — `'agents'` (default), `'hub'`, or `'all'`.
|
|
91
122
|
|
|
92
123
|
### network_memory_detail
|
|
93
124
|
|
|
94
|
-
- **What it does:** Fetches the full content behind a
|
|
95
|
-
- **When to call:** A `memory_search` result came from the
|
|
125
|
+
- **What it does:** Fetches the full content behind a team search hit.
|
|
126
|
+
- **When to call:** A `memory_search` result came from the team and you need the full shared memory content.
|
|
96
127
|
- **Parameters:** `remoteHitId`.
|
|
97
128
|
|
|
98
129
|
### task_share / task_unshare
|
|
99
130
|
|
|
100
|
-
- **What they do:** Share a local task to the
|
|
131
|
+
- **What they do:** Share a local task to the team, or remove it later.
|
|
101
132
|
- **When to call:** A task is valuable to your group or to the whole team and should be discoverable via shared search.
|
|
102
133
|
- **Parameters:** `taskId`, plus sharing visibility/scope when required.
|
|
103
134
|
|
|
104
135
|
### network_skill_pull
|
|
105
136
|
|
|
106
|
-
- **What it does:** Pulls a
|
|
107
|
-
- **When to call:** `skill_search` found a useful
|
|
137
|
+
- **What it does:** Pulls a team-shared skill bundle down into local storage.
|
|
138
|
+
- **When to call:** `skill_search` found a useful team skill and you want to use it locally or offline.
|
|
108
139
|
- **Parameters:** `skillId`.
|
|
109
140
|
|
|
110
141
|
### network_team_info
|
|
111
142
|
|
|
112
|
-
- **What it does:** Returns current
|
|
143
|
+
- **What it does:** Returns current team server connection information, user, role, and groups.
|
|
113
144
|
- **When to call:** You need to confirm whether team sharing is configured or which groups the current client belongs to.
|
|
145
|
+
- **Call this first before:** `memory_share(... target='hub'|'both')`, `memory_unshare(... target='hub'|'all')`, `task_share`, `task_unshare`, `skill_publish(... target='hub')`, `skill_unpublish(... target='hub'|'all')`, or `network_skill_pull`.
|
|
114
146
|
- **Parameters:** none.
|
|
115
147
|
|
|
116
148
|
### memory_timeline
|
|
@@ -147,13 +179,19 @@ This skill describes how to use the MemOS memory tools so you can reliably searc
|
|
|
147
179
|
6. **You need a capability/guide that you don't have**
|
|
148
180
|
→ Call `skill_search(query="...", scope="mix")` to discover available skills.
|
|
149
181
|
|
|
150
|
-
7. **You have shared knowledge useful to all agents**
|
|
151
|
-
→ Call `memory_write_public(content="...")
|
|
182
|
+
7. **You have new shared knowledge useful to all local agents**
|
|
183
|
+
→ Call `memory_write_public(content="...")`.
|
|
184
|
+
|
|
185
|
+
8. **You already have an existing memory chunk and want to expose or hide it**
|
|
186
|
+
→ Call `memory_share(chunkId="...", target="agents|hub|both")` or `memory_unshare(chunkId="...", target="agents|hub|all")`.
|
|
187
|
+
|
|
188
|
+
9. **You are about to do anything team-sharing-related**
|
|
189
|
+
→ Call `network_team_info()` first if team server availability is uncertain.
|
|
152
190
|
|
|
153
|
-
|
|
154
|
-
→
|
|
191
|
+
10. **You want to share/stop sharing a skill with local agents or team**
|
|
192
|
+
→ Prefer `skill_publish(skillId="...", target="agents|hub", visibility=...)` and `skill_unpublish(skillId="...", target="agents|hub|all")`.
|
|
155
193
|
|
|
156
|
-
|
|
194
|
+
11. **User asks where to see or manage their memories**
|
|
157
195
|
→ Call `memory_viewer()` and share the URL.
|
|
158
196
|
|
|
159
197
|
## Writing good search queries
|
|
@@ -168,6 +206,6 @@ This skill describes how to use the MemOS memory tools so you can reliably searc
|
|
|
168
206
|
Each memory is tagged with an `owner` (e.g. `agent:main`, `agent:sales-bot`). This is handled **automatically** — you do not need to pass any owner parameter.
|
|
169
207
|
|
|
170
208
|
- **Your memories:** All tools (`memory_search`, `memory_get`, `memory_timeline`) automatically scope queries to your agent's own memories.
|
|
171
|
-
- **
|
|
209
|
+
- **Local shared memories:** Memories marked as local shared are visible to all agents in the same OpenClaw workspace. Use `memory_write_public` to create them, or `memory_share(target='agents')` to expose an existing chunk.
|
|
172
210
|
- **Cross-agent isolation:** You cannot see memories owned by other agents (unless they are public).
|
|
173
211
|
- **How it works:** The system identifies your agent ID from the OpenClaw runtime context and applies owner filtering automatically on every search, recall, and retrieval.
|
package/src/capture/index.ts
CHANGED
|
@@ -33,6 +33,9 @@ const SENTINEL_FAST_RE = new RegExp(
|
|
|
33
33
|
const ENVELOPE_PREFIX_RE =
|
|
34
34
|
/^\s*\[(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)\s+\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}(?::\d{2})?\s+[A-Z]{3}[+-]\d{1,2}\]\s*/;
|
|
35
35
|
|
|
36
|
+
const ENVELOPE_EXTRACT_RE =
|
|
37
|
+
/^\s*\[(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)\s+(\d{4}-\d{2}-\d{2})\s+(\d{2}:\d{2}(?::\d{2})?)\s+([A-Z]{3}[+-]\d{1,2})\]/;
|
|
38
|
+
|
|
36
39
|
/**
|
|
37
40
|
* Extract writable messages from a conversation turn.
|
|
38
41
|
*
|
|
@@ -47,9 +50,11 @@ export function captureMessages(
|
|
|
47
50
|
evidenceTag: string,
|
|
48
51
|
log: Logger,
|
|
49
52
|
owner?: string,
|
|
53
|
+
userSearchTime?: number,
|
|
50
54
|
): ConversationMessage[] {
|
|
51
55
|
const now = Date.now();
|
|
52
56
|
const result: ConversationMessage[] = [];
|
|
57
|
+
let lastTimestamp = 0;
|
|
53
58
|
|
|
54
59
|
for (const msg of messages) {
|
|
55
60
|
const role = msg.role as Role;
|
|
@@ -74,10 +79,19 @@ export function captureMessages(
|
|
|
74
79
|
}
|
|
75
80
|
if (!content.trim()) continue;
|
|
76
81
|
|
|
82
|
+
let ts: number;
|
|
83
|
+
if (role === "user" && userSearchTime && userSearchTime > 0) {
|
|
84
|
+
ts = userSearchTime;
|
|
85
|
+
} else {
|
|
86
|
+
ts = now;
|
|
87
|
+
}
|
|
88
|
+
if (ts <= lastTimestamp) ts = lastTimestamp + 1;
|
|
89
|
+
lastTimestamp = ts;
|
|
90
|
+
|
|
77
91
|
result.push({
|
|
78
92
|
role,
|
|
79
93
|
content,
|
|
80
|
-
timestamp:
|
|
94
|
+
timestamp: ts,
|
|
81
95
|
turnId,
|
|
82
96
|
sessionKey,
|
|
83
97
|
toolName: role === "tool" ? msg.toolName : undefined,
|
|
@@ -149,6 +163,20 @@ export function stripInboundMetadata(text: string): string {
|
|
|
149
163
|
return stripEnvelopePrefix(result.join("\n")).trim();
|
|
150
164
|
}
|
|
151
165
|
|
|
166
|
+
function extractEnvelopeTimestamp(text: string): number | null {
|
|
167
|
+
const m = ENVELOPE_EXTRACT_RE.exec(text);
|
|
168
|
+
if (!m) return null;
|
|
169
|
+
const [, date, time, tz] = m;
|
|
170
|
+
const timeStr = time.includes(":") && time.split(":").length === 3 ? time : time + ":00";
|
|
171
|
+
const offsetMatch = tz.match(/([+-])(\d{1,2})$/);
|
|
172
|
+
const offsetStr = offsetMatch
|
|
173
|
+
? `${offsetMatch[1]}${offsetMatch[2].padStart(2, "0")}:00`
|
|
174
|
+
: "+00:00";
|
|
175
|
+
const iso = `${date}T${timeStr}${offsetStr}`;
|
|
176
|
+
const ts = new Date(iso).getTime();
|
|
177
|
+
return Number.isNaN(ts) ? null : ts;
|
|
178
|
+
}
|
|
179
|
+
|
|
152
180
|
function stripEnvelopePrefix(text: string): string {
|
|
153
181
|
return text.replace(ENVELOPE_PREFIX_RE, "");
|
|
154
182
|
}
|
package/src/client/connector.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Logger, MemosLocalConfig } from "../types";
|
|
2
|
-
import type {
|
|
2
|
+
import type { UserRole, UserStatus } from "../sharing/types";
|
|
3
3
|
import type { SqliteStore } from "../storage/sqlite";
|
|
4
4
|
import { hubRequestJson, normalizeHubUrl } from "./hub";
|
|
5
5
|
|
|
@@ -20,7 +20,6 @@ export interface HubStatusInfo {
|
|
|
20
20
|
username: string;
|
|
21
21
|
role: UserRole;
|
|
22
22
|
status: UserStatus | string;
|
|
23
|
-
groups: GroupInfo[];
|
|
24
23
|
};
|
|
25
24
|
}
|
|
26
25
|
|
|
@@ -77,7 +76,6 @@ export async function getHubStatus(store: SqliteStore, config: MemosLocalConfig)
|
|
|
77
76
|
username: conn.username || "",
|
|
78
77
|
role: "member",
|
|
79
78
|
status: "pending",
|
|
80
|
-
groups: [],
|
|
81
79
|
},
|
|
82
80
|
};
|
|
83
81
|
}
|
|
@@ -99,13 +97,6 @@ export async function getHubStatus(store: SqliteStore, config: MemosLocalConfig)
|
|
|
99
97
|
username: String(me.username ?? ""),
|
|
100
98
|
role: String(me.role ?? "member") as UserRole,
|
|
101
99
|
status: String(me.status ?? "active"),
|
|
102
|
-
groups: Array.isArray(me.groups)
|
|
103
|
-
? me.groups.map((group: any) => ({
|
|
104
|
-
id: String(group.id),
|
|
105
|
-
name: String(group.name),
|
|
106
|
-
description: typeof group.description === "string" ? group.description : undefined,
|
|
107
|
-
}))
|
|
108
|
-
: [],
|
|
109
100
|
},
|
|
110
101
|
};
|
|
111
102
|
}
|
|
@@ -118,7 +109,6 @@ export async function getHubStatus(store: SqliteStore, config: MemosLocalConfig)
|
|
|
118
109
|
username: conn.username || "",
|
|
119
110
|
role: "member",
|
|
120
111
|
status: "rejected",
|
|
121
|
-
groups: [],
|
|
122
112
|
},
|
|
123
113
|
};
|
|
124
114
|
}
|
|
@@ -141,13 +131,6 @@ export async function getHubStatus(store: SqliteStore, config: MemosLocalConfig)
|
|
|
141
131
|
username: String(me.username ?? ""),
|
|
142
132
|
role: String(me.role ?? "member") as UserRole,
|
|
143
133
|
status: String(me.status ?? "active"),
|
|
144
|
-
groups: Array.isArray(me.groups)
|
|
145
|
-
? me.groups.map((group: any) => ({
|
|
146
|
-
id: String(group.id),
|
|
147
|
-
name: String(group.name),
|
|
148
|
-
description: typeof group.description === "string" ? group.description : undefined,
|
|
149
|
-
}))
|
|
150
|
-
: [],
|
|
151
134
|
},
|
|
152
135
|
};
|
|
153
136
|
} catch {
|
|
@@ -166,13 +149,24 @@ export async function autoJoinHub(
|
|
|
166
149
|
throw new Error("hubAddress and teamToken are required for auto-join");
|
|
167
150
|
}
|
|
168
151
|
const hubUrl = normalizeHubUrl(hubAddress);
|
|
169
|
-
const
|
|
170
|
-
const
|
|
152
|
+
const osModule = typeof globalThis.process !== "undefined" ? await import("os") : null;
|
|
153
|
+
const hostname = osModule ? osModule.hostname() : "unknown";
|
|
154
|
+
const username = osModule ? osModule.userInfo().username : "user";
|
|
155
|
+
let clientIp = "";
|
|
156
|
+
if (osModule) {
|
|
157
|
+
const nets = osModule.networkInterfaces();
|
|
158
|
+
for (const name of Object.keys(nets)) {
|
|
159
|
+
for (const net of nets[name] ?? []) {
|
|
160
|
+
if (net.family === "IPv4" && !net.internal) { clientIp = net.address; break; }
|
|
161
|
+
}
|
|
162
|
+
if (clientIp) break;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
171
165
|
|
|
172
166
|
log.info(`Joining Hub at ${hubUrl} as "${username}"...`);
|
|
173
167
|
const result = await hubRequestJson(hubUrl, "", "/api/v1/hub/join", {
|
|
174
168
|
method: "POST",
|
|
175
|
-
body: JSON.stringify({ teamToken, username, deviceName: hostname }),
|
|
169
|
+
body: JSON.stringify({ teamToken, username, deviceName: hostname, clientIp }),
|
|
176
170
|
}) as any;
|
|
177
171
|
|
|
178
172
|
if (result.status === "pending") {
|
package/src/client/hub.ts
CHANGED
|
@@ -157,16 +157,34 @@ export async function hubUpdateUsername(
|
|
|
157
157
|
return result;
|
|
158
158
|
}
|
|
159
159
|
|
|
160
|
+
let _cachedClientIp: string | null = null;
|
|
161
|
+
function getClientIp(): string {
|
|
162
|
+
if (_cachedClientIp !== null) return _cachedClientIp;
|
|
163
|
+
try {
|
|
164
|
+
const os = require("os");
|
|
165
|
+
const nets = os.networkInterfaces();
|
|
166
|
+
for (const name of Object.keys(nets)) {
|
|
167
|
+
for (const net of nets[name] ?? []) {
|
|
168
|
+
if (net.family === "IPv4" && !net.internal) { _cachedClientIp = net.address; return _cachedClientIp!; }
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
} catch { /* browser or no os module */ }
|
|
172
|
+
_cachedClientIp = "";
|
|
173
|
+
return "";
|
|
174
|
+
}
|
|
175
|
+
|
|
160
176
|
export async function hubRequestJson(
|
|
161
177
|
hubUrl: string,
|
|
162
178
|
userToken: string,
|
|
163
179
|
route: string,
|
|
164
180
|
init: RequestInit = {},
|
|
165
181
|
): Promise<unknown> {
|
|
182
|
+
const clientIp = getClientIp();
|
|
166
183
|
const res = await fetch(`${normalizeHubUrl(hubUrl)}${route}`, {
|
|
167
184
|
...init,
|
|
168
185
|
headers: {
|
|
169
186
|
authorization: `Bearer ${userToken}`,
|
|
187
|
+
...(clientIp ? { "x-client-ip": clientIp } : {}),
|
|
170
188
|
...(init.body ? { "content-type": "application/json" } : {}),
|
|
171
189
|
...(init.headers ?? {}),
|
|
172
190
|
},
|
package/src/client/skill-sync.ts
CHANGED
|
@@ -89,6 +89,20 @@ export async function publishSkillBundleToHub(
|
|
|
89
89
|
}) as Promise<{ skillId: string; visibility: "public" | "group" }>;
|
|
90
90
|
}
|
|
91
91
|
|
|
92
|
+
export async function unpublishSkillBundleFromHub(
|
|
93
|
+
store: SqliteStore,
|
|
94
|
+
ctx: PluginContext,
|
|
95
|
+
input: { skillId: string; hubAddress?: string; userToken?: string },
|
|
96
|
+
): Promise<{ ok: boolean }> {
|
|
97
|
+
const client = await resolveHubClient(store, ctx, { hubAddress: input.hubAddress, userToken: input.userToken });
|
|
98
|
+
return hubRequestJson(client.hubUrl, client.userToken, "/api/v1/hub/skills/unpublish", {
|
|
99
|
+
method: "POST",
|
|
100
|
+
body: JSON.stringify({
|
|
101
|
+
sourceSkillId: input.skillId,
|
|
102
|
+
}),
|
|
103
|
+
}) as Promise<{ ok: boolean }>;
|
|
104
|
+
}
|
|
105
|
+
|
|
92
106
|
export async function fetchHubSkillBundle(
|
|
93
107
|
store: SqliteStore,
|
|
94
108
|
ctx: PluginContext,
|
package/src/hub/server.ts
CHANGED
|
@@ -192,9 +192,14 @@ export class HubServer {
|
|
|
192
192
|
return this.json(res, 403, { error: "invalid_team_token" });
|
|
193
193
|
}
|
|
194
194
|
const username = String(body.username || `user-${randomUUID().slice(0, 8)}`);
|
|
195
|
+
const joinIp = (typeof body.clientIp === "string" && body.clientIp)
|
|
196
|
+
|| (req.headers["x-client-ip"] as string)?.trim()
|
|
197
|
+
|| (req.headers["x-forwarded-for"] as string)?.split(",")[0]?.trim()
|
|
198
|
+
|| req.socket.remoteAddress || "";
|
|
195
199
|
const existingUsers = this.opts.store.listHubUsers();
|
|
196
200
|
const existingUser = existingUsers.find(u => u.username === username);
|
|
197
201
|
if (existingUser) {
|
|
202
|
+
try { this.opts.store.updateHubUserActivity(existingUser.id, joinIp); } catch { /* best-effort */ }
|
|
198
203
|
if (existingUser.status === "active") {
|
|
199
204
|
const token = issueUserToken(
|
|
200
205
|
{ userId: existingUser.id, username: existingUser.username, role: existingUser.role, status: "active" },
|
|
@@ -216,6 +221,7 @@ export class HubServer {
|
|
|
216
221
|
username,
|
|
217
222
|
deviceName: typeof body.deviceName === "string" ? body.deviceName : undefined,
|
|
218
223
|
});
|
|
224
|
+
try { this.opts.store.updateHubUserActivity(user.id, joinIp); } catch { /* best-effort */ }
|
|
219
225
|
this.opts.log.info(`Hub: user "${username}" (${user.id}) registered as pending, awaiting admin approval`);
|
|
220
226
|
return this.json(res, 200, { status: "pending", userId: user.id });
|
|
221
227
|
}
|
|
@@ -272,9 +278,11 @@ export class HubServer {
|
|
|
272
278
|
}
|
|
273
279
|
const updated = this.userManager.updateUsername(auth.userId, newUsername);
|
|
274
280
|
if (!updated) return this.json(res, 404, { error: "not_found" });
|
|
281
|
+
const ttlMs = updated.role === "admin" ? 3650 * 24 * 60 * 60 * 1000 : undefined;
|
|
275
282
|
const newToken = issueUserToken(
|
|
276
283
|
{ userId: updated.id, username: newUsername, role: updated.role, status: updated.status },
|
|
277
284
|
this.authSecret,
|
|
285
|
+
ttlMs,
|
|
278
286
|
);
|
|
279
287
|
this.userManager.approveUser(updated.id, newToken);
|
|
280
288
|
this.opts.log.info(`Hub: user "${auth.userId}" renamed to "${newUsername}"`);
|
|
@@ -306,91 +314,62 @@ export class HubServer {
|
|
|
306
314
|
if (req.method === "GET" && routePath === "/api/v1/hub/admin/users") {
|
|
307
315
|
if (auth.role !== "admin") return this.json(res, 403, { error: "forbidden" });
|
|
308
316
|
const users = this.opts.store.listHubUsers().filter(u => u.status === "active");
|
|
309
|
-
|
|
317
|
+
const contribs = this.opts.store.getHubUserContributions();
|
|
318
|
+
return this.json(res, 200, { users: users.map(u => {
|
|
319
|
+
const c = contribs[u.id] || { memoryCount: 0, taskCount: 0, skillCount: 0 };
|
|
320
|
+
return {
|
|
321
|
+
id: u.id, username: u.username, role: u.role, status: u.status,
|
|
322
|
+
deviceName: u.deviceName, createdAt: u.createdAt, approvedAt: u.approvedAt,
|
|
323
|
+
lastIp: u.lastIp || "", lastActiveAt: u.lastActiveAt,
|
|
324
|
+
memoryCount: c.memoryCount, taskCount: c.taskCount, skillCount: c.skillCount,
|
|
325
|
+
};
|
|
326
|
+
}) });
|
|
310
327
|
}
|
|
311
328
|
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
if (req.method === "GET" && routePath === "/api/v1/hub/groups") {
|
|
329
|
+
if (req.method === "POST" && routePath === "/api/v1/hub/admin/change-role") {
|
|
315
330
|
if (auth.role !== "admin") return this.json(res, 403, { error: "forbidden" });
|
|
316
|
-
const
|
|
317
|
-
|
|
331
|
+
const body = await this.readJson(req);
|
|
332
|
+
const userId = String(body?.userId || "");
|
|
333
|
+
const newRole = String(body?.role || "");
|
|
334
|
+
if (!userId || (newRole !== "admin" && newRole !== "member")) return this.json(res, 400, { error: "invalid_params" });
|
|
335
|
+
const user = this.opts.store.getHubUser(userId);
|
|
336
|
+
if (!user || user.status !== "active") return this.json(res, 404, { error: "not_found" });
|
|
337
|
+
const updatedUser = { ...user, role: newRole as "admin" | "member" };
|
|
338
|
+
this.opts.store.upsertHubUser(updatedUser);
|
|
339
|
+
this.opts.log.info(`Hub: admin "${auth.userId}" changed role of "${userId}" to "${newRole}"`);
|
|
340
|
+
return this.json(res, 200, { ok: true, role: newRole });
|
|
318
341
|
}
|
|
319
342
|
|
|
320
|
-
if (req.method === "POST" && routePath === "/api/v1/hub/
|
|
343
|
+
if (req.method === "POST" && routePath === "/api/v1/hub/admin/rename-user") {
|
|
321
344
|
if (auth.role !== "admin") return this.json(res, 403, { error: "forbidden" });
|
|
322
345
|
const body = await this.readJson(req);
|
|
323
|
-
const
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
id: groupId,
|
|
328
|
-
name,
|
|
329
|
-
description: String(body.description || ""),
|
|
330
|
-
createdAt: Date.now(),
|
|
331
|
-
});
|
|
332
|
-
return this.json(res, 201, { id: groupId, name });
|
|
333
|
-
}
|
|
334
|
-
|
|
335
|
-
const groupDetailMatch = routePath.match(/^\/api\/v1\/hub\/groups\/([^/]+)$/);
|
|
336
|
-
if (groupDetailMatch) {
|
|
337
|
-
const groupId = decodeURIComponent(groupDetailMatch[1]);
|
|
338
|
-
|
|
339
|
-
if (req.method === "GET") {
|
|
340
|
-
if (auth.role !== "admin") return this.json(res, 403, { error: "forbidden" });
|
|
341
|
-
const group = this.opts.store.getHubGroupById(groupId);
|
|
342
|
-
if (!group) return this.json(res, 404, { error: "not_found" });
|
|
343
|
-
const members = this.opts.store.listHubGroupMembers(groupId);
|
|
344
|
-
return this.json(res, 200, { ...group, members });
|
|
346
|
+
const userId = String(body?.userId || "");
|
|
347
|
+
const newUsername = String(body?.username || "").trim();
|
|
348
|
+
if (!userId || !newUsername || newUsername.length < 2 || newUsername.length > 32) {
|
|
349
|
+
return this.json(res, 400, { error: "invalid_params", message: "userId and username (2-32 chars) required" });
|
|
345
350
|
}
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
if (auth.role !== "admin") return this.json(res, 403, { error: "forbidden" });
|
|
349
|
-
const existing = this.opts.store.getHubGroupById(groupId);
|
|
350
|
-
if (!existing) return this.json(res, 404, { error: "not_found" });
|
|
351
|
-
const body = await this.readJson(req);
|
|
352
|
-
this.opts.store.upsertHubGroup({
|
|
353
|
-
id: groupId,
|
|
354
|
-
name: String(body.name || existing.name).trim(),
|
|
355
|
-
description: String(body.description ?? existing.description),
|
|
356
|
-
createdAt: existing.createdAt,
|
|
357
|
-
});
|
|
358
|
-
return this.json(res, 200, { ok: true });
|
|
359
|
-
}
|
|
360
|
-
|
|
361
|
-
if (req.method === "DELETE") {
|
|
362
|
-
if (auth.role !== "admin") return this.json(res, 403, { error: "forbidden" });
|
|
363
|
-
const deleted = this.opts.store.deleteHubGroup(groupId);
|
|
364
|
-
if (!deleted) return this.json(res, 404, { error: "not_found" });
|
|
365
|
-
return this.json(res, 200, { ok: true });
|
|
351
|
+
if (this.userManager.isUsernameTaken(newUsername, userId)) {
|
|
352
|
+
return this.json(res, 409, { error: "username_taken", message: "Username already in use" });
|
|
366
353
|
}
|
|
354
|
+
const user = this.opts.store.getHubUser(userId);
|
|
355
|
+
if (!user || user.status !== "active") return this.json(res, 404, { error: "not_found" });
|
|
356
|
+
const updated = { ...user, username: newUsername };
|
|
357
|
+
this.opts.store.upsertHubUser(updated);
|
|
358
|
+
this.opts.log.info(`Hub: admin "${auth.userId}" renamed user "${userId}" to "${newUsername}"`);
|
|
359
|
+
return this.json(res, 200, { ok: true, username: newUsername });
|
|
367
360
|
}
|
|
368
361
|
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
const
|
|
372
|
-
|
|
373
|
-
if (
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
const user = this.opts.store.getHubUser(userId);
|
|
381
|
-
if (!user) return this.json(res, 404, { error: "user_not_found" });
|
|
382
|
-
this.opts.store.addHubGroupMember(groupId, userId);
|
|
383
|
-
return this.json(res, 200, { ok: true });
|
|
384
|
-
}
|
|
385
|
-
|
|
386
|
-
if (req.method === "DELETE") {
|
|
387
|
-
if (auth.role !== "admin") return this.json(res, 403, { error: "forbidden" });
|
|
388
|
-
const body = await this.readJson(req);
|
|
389
|
-
const userId = String(body.userId || "");
|
|
390
|
-
if (!userId) return this.json(res, 400, { error: "userId_required" });
|
|
391
|
-
this.opts.store.removeHubGroupMember(groupId, userId);
|
|
392
|
-
return this.json(res, 200, { ok: true });
|
|
393
|
-
}
|
|
362
|
+
if (req.method === "POST" && routePath === "/api/v1/hub/admin/remove-user") {
|
|
363
|
+
if (auth.role !== "admin") return this.json(res, 403, { error: "forbidden" });
|
|
364
|
+
const body = await this.readJson(req);
|
|
365
|
+
const userId = String(body?.userId || "");
|
|
366
|
+
if (!userId) return this.json(res, 400, { error: "missing_user_id" });
|
|
367
|
+
if (userId === auth.userId) return this.json(res, 400, { error: "cannot_remove_self" });
|
|
368
|
+
const cleanResources = body?.cleanResources === true;
|
|
369
|
+
const deleted = this.opts.store.deleteHubUser(userId, cleanResources);
|
|
370
|
+
if (!deleted) return this.json(res, 404, { error: "not_found" });
|
|
371
|
+
this.opts.log.info(`Hub: admin "${auth.userId}" removed user "${userId}" (cleanResources=${cleanResources})`);
|
|
372
|
+
return this.json(res, 200, { ok: true });
|
|
394
373
|
}
|
|
395
374
|
|
|
396
375
|
if (req.method === "POST" && routePath === "/api/v1/hub/tasks/share") {
|
|
@@ -639,8 +618,12 @@ export class HubServer {
|
|
|
639
618
|
if (adminTaskDeleteMatch) {
|
|
640
619
|
if (auth.role !== "admin") return this.json(res, 403, { error: "forbidden" });
|
|
641
620
|
const taskId = decodeURIComponent(adminTaskDeleteMatch[1]);
|
|
621
|
+
const taskInfo = this.opts.store.getHubTaskById(taskId);
|
|
642
622
|
const deleted = this.opts.store.deleteHubTaskById(taskId);
|
|
643
623
|
if (!deleted) return this.json(res, 404, { error: "not_found" });
|
|
624
|
+
if (taskInfo) {
|
|
625
|
+
this.opts.store.insertHubNotification({ id: randomUUID(), userId: taskInfo.sourceUserId, type: "resource_removed", resource: "task", title: taskInfo.title });
|
|
626
|
+
}
|
|
644
627
|
return this.json(res, 200, { ok: true });
|
|
645
628
|
}
|
|
646
629
|
|
|
@@ -654,8 +637,12 @@ export class HubServer {
|
|
|
654
637
|
if (adminSkillDeleteMatch) {
|
|
655
638
|
if (auth.role !== "admin") return this.json(res, 403, { error: "forbidden" });
|
|
656
639
|
const skillId = decodeURIComponent(adminSkillDeleteMatch[1]);
|
|
640
|
+
const skillInfo = this.opts.store.getHubSkillById(skillId);
|
|
657
641
|
const deleted = this.opts.store.deleteHubSkillById(skillId);
|
|
658
642
|
if (!deleted) return this.json(res, 404, { error: "not_found" });
|
|
643
|
+
if (skillInfo) {
|
|
644
|
+
this.opts.store.insertHubNotification({ id: randomUUID(), userId: skillInfo.sourceUserId, type: "resource_removed", resource: "skill", title: skillInfo.name });
|
|
645
|
+
}
|
|
659
646
|
return this.json(res, 200, { ok: true });
|
|
660
647
|
}
|
|
661
648
|
|
|
@@ -669,8 +656,12 @@ export class HubServer {
|
|
|
669
656
|
if (adminMemoryDeleteMatch) {
|
|
670
657
|
if (auth.role !== "admin") return this.json(res, 403, { error: "forbidden" });
|
|
671
658
|
const memoryId = decodeURIComponent(adminMemoryDeleteMatch[1]);
|
|
659
|
+
const memInfo = this.opts.store.getHubMemoryById(memoryId);
|
|
672
660
|
const deleted = this.opts.store.deleteHubMemoryById(memoryId);
|
|
673
661
|
if (!deleted) return this.json(res, 404, { error: "not_found" });
|
|
662
|
+
if (memInfo) {
|
|
663
|
+
this.opts.store.insertHubNotification({ id: randomUUID(), userId: memInfo.sourceUserId, type: "resource_removed", resource: "memory", title: memInfo.summary || memInfo.id });
|
|
664
|
+
}
|
|
674
665
|
return this.json(res, 200, { ok: true });
|
|
675
666
|
}
|
|
676
667
|
|
|
@@ -693,6 +684,25 @@ export class HubServer {
|
|
|
693
684
|
});
|
|
694
685
|
}
|
|
695
686
|
|
|
687
|
+
if (req.method === "GET" && routePath === "/api/v1/hub/notifications") {
|
|
688
|
+
const unread = (new URL(req.url!, `http://${req.headers.host}`)).searchParams.get("unread") === "1";
|
|
689
|
+
const list = this.opts.store.listHubNotifications(auth.userId, { unreadOnly: unread, limit: 50 });
|
|
690
|
+
const unreadCount = this.opts.store.countUnreadHubNotifications(auth.userId);
|
|
691
|
+
return this.json(res, 200, { notifications: list, unreadCount });
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
if (req.method === "POST" && routePath === "/api/v1/hub/notifications/read") {
|
|
695
|
+
const body = await this.readJson(req);
|
|
696
|
+
const ids = Array.isArray(body.ids) ? body.ids as string[] : undefined;
|
|
697
|
+
this.opts.store.markHubNotificationsRead(auth.userId, ids);
|
|
698
|
+
return this.json(res, 200, { ok: true });
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
if (req.method === "POST" && routePath === "/api/v1/hub/notifications/clear") {
|
|
702
|
+
this.opts.store.clearHubNotifications(auth.userId);
|
|
703
|
+
return this.json(res, 200, { ok: true });
|
|
704
|
+
}
|
|
705
|
+
|
|
696
706
|
return this.json(res, 404, { error: "not_found" });
|
|
697
707
|
}
|
|
698
708
|
|
|
@@ -706,6 +716,10 @@ export class HubServer {
|
|
|
706
716
|
if (!user || user.status !== "active") return null;
|
|
707
717
|
const hash = createHash("sha256").update(token).digest("hex");
|
|
708
718
|
if (user.tokenHash !== hash) return null;
|
|
719
|
+
const clientIp = (req.headers["x-client-ip"] as string)?.trim()
|
|
720
|
+
|| (req.headers["x-forwarded-for"] as string)?.split(",")[0]?.trim()
|
|
721
|
+
|| req.socket.remoteAddress || "";
|
|
722
|
+
try { this.opts.store.updateHubUserActivity(user.id, clientIp); } catch { /* best-effort */ }
|
|
709
723
|
return {
|
|
710
724
|
userId: user.id,
|
|
711
725
|
username: user.username,
|