@sleep2agi/commhub-server 0.9.0-preview.281 → 0.9.0-preview.283
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/build-info.json +2 -2
- package/package.json +1 -1
- package/src/agent-acl-slice3-http.test.ts +3 -2
- package/src/api-host-supervisors-source-capabilities.test.ts +107 -0
- package/src/auth_login_guard.test.ts +15 -0
- package/src/auth_login_guard.ts +20 -1
- package/src/board-grants.test.ts +134 -0
- package/src/broadcast-attribution.test.ts +93 -0
- package/src/build-commit-report-http.test.ts +10 -0
- package/src/clone-node-adopted-db.test.ts +78 -0
- package/src/clone-node.ts +5 -1
- package/src/create-node-department.test.ts +145 -0
- package/src/create-node.ts +35 -0
- package/src/db.ts +11 -0
- package/src/department-heads.ts +3 -0
- package/src/expiry-counters.test.ts +50 -1
- package/src/expiry-counters.ts +31 -9
- package/src/mcp-write-network-resolution.test.ts +36 -0
- package/src/node-attrs-validate.ts +34 -0
- package/src/node-attrs.test.ts +32 -0
- package/src/node-config-last-update.test.ts +103 -1
- package/src/node-config-last-update.ts +70 -5
- package/src/node-daemon-bindings.ts +9 -0
- package/src/node-description-http.test.ts +121 -0
- package/src/node-description.test.ts +34 -0
- package/src/node-grants-http.test.ts +239 -0
- package/src/node-grants.ts +234 -0
- package/src/node-inbox-allowlist-http.test.ts +35 -0
- package/src/node-permissions.ts +37 -2
- package/src/opencode-v2-catalog.test.ts +22 -1
- package/src/opencode-v2-catalog.ts +36 -3
- package/src/peer-allowlist.test.ts +29 -0
- package/src/registration-switch-http.test.ts +60 -0
- package/src/reply-bare-infer-4315.test.ts +86 -0
- package/src/requirements.ts +29 -4
- package/src/schedule-agent.ts +45 -10
- package/src/scheduled-tasks-http.test.ts +25 -0
- package/src/scheduled-tasks.ts +46 -2
- package/src/server.ts +132 -11
- package/src/steer-send-message.test.ts +121 -0
- package/src/task-access.ts +21 -1
- package/src/tool-audience-http.test.ts +5 -0
- package/src/tools.ts +147 -42
package/src/requirements.ts
CHANGED
|
@@ -14,6 +14,7 @@ import { aggregateStats, parseStatsQuery, type StatsRow } from "./requirements-s
|
|
|
14
14
|
import { addHumanNetworkScope, canRestWriteNetwork, canRestWriteNetworkAsHuman, resolveRestWriteNetworkId, type RestNetworkScope } from "./network-scope.js";
|
|
15
15
|
import { isAgentRestricted, restrictedNetworkIds, visibleAgents } from "./agent-access.js";
|
|
16
16
|
import { nodeDecide, nodeIdentity, nodePermissionDeniedBody, nodePermissionsFlag, type NodeIdentity, type Verdict } from "./node-permissions.js";
|
|
17
|
+
import { boardGrantForCard, boardScopeForNode } from "./node-grants.js";
|
|
17
18
|
import {
|
|
18
19
|
addProjectVisibilityScope, addTaskVisibilityScope, canDeleteTask, canEditTask, deletesAsHeadOnly, headOnlyEditScope, canParticipantEditTask, canSeeTask, canUseProject, deleteTaskGrantsForProject, projectUseResolver,
|
|
19
20
|
cardAssignedToNode, isTaskScoped, PARTICIPANT_EDIT_FIELDS, shouldAuditDenied, taskPermissionsResolver, type TaskCaller,
|
|
@@ -149,8 +150,13 @@ function nodeIdent(ctx: RequirementsRequestContext): NodeIdentity | null {
|
|
|
149
150
|
function nodeTaskCaller(ctx: RequirementsRequestContext): TaskCaller {
|
|
150
151
|
const id = nodeIdent(ctx);
|
|
151
152
|
if (!id?.ownerUserId) return null;
|
|
152
|
-
|
|
153
|
-
|
|
153
|
+
// 第二期 board:只有「这个节点**确实有** board 授权」时才带上额外范围。
|
|
154
|
+
// 没授权的节点返回 null / 原样对象 ⇒ 可见性 SQL 逐字节不变。
|
|
155
|
+
const board = id.networkId ? boardScopeForNode(id.networkId, id.logKey) : null;
|
|
156
|
+
if (id.mode === "restricted") return { userId: id.ownerUserId, node: { id: id.logKey, only: true }, ...(board ? { board } : {}) };
|
|
157
|
+
if (nodePermissionsFlag() === "enforce") return { userId: id.ownerUserId, node: { id: id.logKey, only: false }, ...(board ? { board } : {}) };
|
|
158
|
+
// 影子模式(默认 log / 未开 enforce):本来就不收窄可见性,节点看到的就是全部卡 ——
|
|
159
|
+
// 这时再挂 board 只会把范围**收窄**到「主人 + 授权」,违反「授权只加不减」。所以这里保持原来的 null。
|
|
154
160
|
return null;
|
|
155
161
|
}
|
|
156
162
|
|
|
@@ -162,6 +168,18 @@ function nodeTaskGate(ctx: RequirementsRequestContext, route: string, row: Row |
|
|
|
162
168
|
const id = nodeIdent(ctx);
|
|
163
169
|
if (!id) return null;
|
|
164
170
|
const sample = row ? `#${row.seq ?? "?"} ${row.requirement_id}` : create?.projectId ?? undefined;
|
|
171
|
+
// 第二期 board:这一刀只管「改已有卡」。boardGrantForCard 已把 readonly 模式的 edit 降成 read,
|
|
172
|
+
// 所以这里拿到 "edit" 就说明真的可写;read 不放行(只读不能改)。
|
|
173
|
+
if (row && id.networkId) {
|
|
174
|
+
const level = boardGrantForCard(id.networkId, id.logKey, row, id.mode);
|
|
175
|
+
if (level === "edit") {
|
|
176
|
+
try {
|
|
177
|
+
logAudit(id.ownerUserId, id.aliases[0] ?? id.nodeId, "requirement_changed_via_node_grant", "requirement",
|
|
178
|
+
row.requirement_id, JSON.stringify({ route, node_id: id.nodeId }), undefined, id.networkId);
|
|
179
|
+
} catch { /* 审计失败不挡写入 */ }
|
|
180
|
+
return null;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
165
183
|
let verdict: Verdict = null;
|
|
166
184
|
if (id.mode === "readonly") verdict = { reason: "mode_readonly", sample };
|
|
167
185
|
else if (id.mode === "restricted") {
|
|
@@ -178,6 +196,13 @@ function nodeTaskGate(ctx: RequirementsRequestContext, route: string, row: Row |
|
|
|
178
196
|
return nodeDecide(id, route, verdict) ? Response.json(nodePermissionDeniedBody(verdict!.reason, route), { status: 403 }) : null;
|
|
179
197
|
}
|
|
180
198
|
|
|
199
|
+
/** 第二期 board:这个节点经授权可写这张卡(edit 级;readonly 模式在 boardGrantForCard 里已降成 read)。 */
|
|
200
|
+
function nodeBoardEdit(ctx: RequirementsRequestContext, row: Row): boolean {
|
|
201
|
+
const id = nodeIdent(ctx);
|
|
202
|
+
if (!id?.networkId) return false;
|
|
203
|
+
return boardGrantForCard(id.networkId, id.logKey, row, id.mode) === "edit";
|
|
204
|
+
}
|
|
205
|
+
|
|
181
206
|
/** 正常模式的节点读到了主人看不见的卡:只记录(执行时 taskCaller 已按主人收窄,读不到)。主人不受任务范围限制时什么都不做。 */
|
|
182
207
|
function nodeReadNote(ctx: RequirementsRequestContext, route: string, row: Row | null): void {
|
|
183
208
|
const id = nodeIdent(ctx);
|
|
@@ -1239,7 +1264,7 @@ function patchRequirement(ctx: RequirementsRequestContext, row: Row, body: Recor
|
|
|
1239
1264
|
const nodeDenied = nodeTaskGate(ctx, "PATCH /api/requirements/:id", row);
|
|
1240
1265
|
if (nodeDenied) return nodeDenied;
|
|
1241
1266
|
const caller = taskCaller(ctx);
|
|
1242
|
-
if (!canEditTask(caller, row)) {
|
|
1267
|
+
if (!canEditTask(caller, row) && !nodeBoardEdit(ctx, row)) {
|
|
1243
1268
|
// 参与人:只放状态和检查项;别的字段点名拒绝。不是参与人 → 与今天一样。
|
|
1244
1269
|
if (!canParticipantEditTask(caller, row)) return taskDenied(ctx, row, "task_read_only");
|
|
1245
1270
|
const other = PATCH_FIELDS.find(k => has(k) && !PARTICIPANT_EDIT_FIELDS.includes(k));
|
|
@@ -2142,7 +2167,7 @@ async function handleRequirementsRequestInner(ctx: RequirementsRequestContext):
|
|
|
2142
2167
|
if (!canWrite(ctx, row.network_id)) return jsonError("permission_denied", 403);
|
|
2143
2168
|
const nodeDenied = nodeTaskGate(ctx, "PATCH /api/requirements/:id/checklist/:id", row);
|
|
2144
2169
|
if (nodeDenied) return nodeDenied;
|
|
2145
|
-
if (!canEditTask(taskCaller(ctx), row) && !canParticipantEditTask(taskCaller(ctx), row)) return taskDenied(ctx, row, "task_read_only");
|
|
2170
|
+
if (!canEditTask(taskCaller(ctx), row) && !canParticipantEditTask(taskCaller(ctx), row) && !nodeBoardEdit(ctx, row)) return taskDenied(ctx, row, "task_read_only");
|
|
2146
2171
|
// 读-改-写在同一个同步段里完成(中间没有 await),同一进程里的两次勾选不会交错。
|
|
2147
2172
|
const items = storedChecklist(row.checklist_json);
|
|
2148
2173
|
const itemId = decodeURIComponent(itemMatch[2]);
|
package/src/schedule-agent.ts
CHANGED
|
@@ -27,6 +27,8 @@ import {
|
|
|
27
27
|
} from "./scheduled-tasks.js";
|
|
28
28
|
import { SCHEDULED_TASK_STORAGE_SELECT } from "./rest-projections.js";
|
|
29
29
|
import { dispatchVerdict, nodePermissionDeniedBody, recordNodePermission, type NodeIdentity } from "./node-permissions.js";
|
|
30
|
+
import { grantLevelForTarget, hasAnyGrant } from "./node-grants.js";
|
|
31
|
+
import { logAudit } from "./db.js";
|
|
30
32
|
|
|
31
33
|
export type AgentScheduleResult = Record<string, unknown> & { ok: boolean };
|
|
32
34
|
|
|
@@ -40,7 +42,9 @@ const fail = (error: string, extra: Record<string, unknown> = {}): AgentSchedule
|
|
|
40
42
|
/** The scope rule. Exported so the mutation tests can pin it. */
|
|
41
43
|
export function nodeMaySeeSchedule(id: NodeIdentity, row: ScheduledRow): boolean {
|
|
42
44
|
if (!id.nodeId || row.network_id !== id.networkId) return false;
|
|
43
|
-
|
|
45
|
+
if (row.target_node_id === id.nodeId || row.created_by_node_id === id.nodeId) return true;
|
|
46
|
+
// 节点管理授权(node-grants.ts):能力 schedules,按目标节点判范围;read / edit 都能看。
|
|
47
|
+
return grantLevelForTarget(id.networkId, id.nodeId, "schedules", row.target_node_id, id.mode) !== null;
|
|
44
48
|
}
|
|
45
49
|
|
|
46
50
|
function visibleRow(id: NodeIdentity, scheduleId: string): ScheduledRow | null {
|
|
@@ -50,12 +54,23 @@ function visibleRow(id: NodeIdentity, scheduleId: string): ScheduledRow | null {
|
|
|
50
54
|
|
|
51
55
|
/** Visible AND created by this node; else the error to return. Exported for the mutation tests. */
|
|
52
56
|
export function nodeMayMutateSchedule(id: NodeIdentity, row: ScheduledRow): boolean {
|
|
53
|
-
|
|
57
|
+
if (!id.nodeId) return false;
|
|
58
|
+
if (row.created_by_node_id === id.nodeId) return true;
|
|
59
|
+
return grantLevelForTarget(id.networkId, id.nodeId, "schedules", row.target_node_id, id.mode) === "edit";
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** 经授权(不是自己建的)改了一条计划:记一行审计,主人在报表里看得到是哪个节点改的。 */
|
|
63
|
+
function auditGrantMutation(id: NodeIdentity, row: ScheduledRow, action: string): void {
|
|
64
|
+
if (!id.nodeId || row.created_by_node_id === id.nodeId) return;
|
|
65
|
+
try {
|
|
66
|
+
logAudit(id.ownerUserId, id.aliases[0] ?? id.nodeId, "schedule_changed_via_node_grant", "scheduled_task", row.schedule_id,
|
|
67
|
+
JSON.stringify({ action, node_id: id.nodeId, target_node_id: row.target_node_id }), undefined, id.networkId);
|
|
68
|
+
} catch { /* 审计失败不挡写入 */ }
|
|
54
69
|
}
|
|
55
70
|
function ownRow(id: NodeIdentity, scheduleId: string): ScheduledRow | AgentScheduleResult {
|
|
56
71
|
const row = visibleRow(id, scheduleId);
|
|
57
72
|
if (!row) return fail("schedule_not_found");
|
|
58
|
-
if (!nodeMayMutateSchedule(id, row)) return fail("not_schedule_creator", { message: "only schedules this node created can be changed" });
|
|
73
|
+
if (!nodeMayMutateSchedule(id, row)) return fail("not_schedule_creator", { message: "only schedules this node created (or that an edit grant covers) can be changed" });
|
|
59
74
|
return row;
|
|
60
75
|
}
|
|
61
76
|
const isRow = (r: ScheduledRow | AgentScheduleResult): r is ScheduledRow => typeof (r as ScheduledRow).schedule_id === "string";
|
|
@@ -83,10 +98,20 @@ function inputError(e: any): AgentScheduleResult {
|
|
|
83
98
|
export function agentListSchedules(id: NodeIdentity, status?: string): AgentScheduleResult {
|
|
84
99
|
if (!id.nodeId) return fail("node_identity_unbound");
|
|
85
100
|
const params: unknown[] = [id.networkId, id.nodeId];
|
|
86
|
-
|
|
101
|
+
// 有 schedules 授权时扫全网(上限 500)再按授权逐条判;没有授权走原来的窄查询。
|
|
102
|
+
const granted = hasAnyGrant(id.networkId, id.nodeId, "schedules");
|
|
103
|
+
let sql = granted
|
|
104
|
+
? `SELECT ${SCHEDULED_TASK_STORAGE_SELECT} FROM scheduled_tasks WHERE network_id = ?1 AND ?2 = ?2`
|
|
105
|
+
: `SELECT ${SCHEDULED_TASK_STORAGE_SELECT} FROM scheduled_tasks WHERE network_id = ?1 AND (target_node_id = ?2 OR created_by_node_id = ?2)`;
|
|
87
106
|
if (status) { sql += " AND status = ?3"; params.push(status); }
|
|
88
|
-
sql += " ORDER BY updated_at DESC LIMIT 200";
|
|
89
|
-
const
|
|
107
|
+
sql += granted ? " ORDER BY updated_at DESC LIMIT 500" : " ORDER BY updated_at DESC LIMIT 200";
|
|
108
|
+
const rawRows = db.all<ScheduledRow>(sql, ...params);
|
|
109
|
+
const rows = (granted ? rawRows.filter(r => nodeMaySeeSchedule(id, r)) : rawRows).map(decodeRowForAgent);
|
|
110
|
+
if (granted) for (const r of rows) {
|
|
111
|
+
const raw = rawRows.find(x => x.schedule_id === (r as Record<string, unknown>).schedule_id);
|
|
112
|
+
if (raw) (r as Record<string, unknown>).access = raw.created_by_node_id === id.nodeId || raw.target_node_id === id.nodeId
|
|
113
|
+
? "own" : nodeMayMutateSchedule(id, raw) ? "grant_edit" : "grant_read";
|
|
114
|
+
}
|
|
90
115
|
// #2935 —— 「周期比单轮工作耗时短」的排程会**永久 skip**:退避只会让它更稀疏,追不上。
|
|
91
116
|
// 数据是现成的(scheduled_task_runs 的 completed_at - created_at),只是以前没人给出来。
|
|
92
117
|
// 这里只**报数**,不改任何调度行为。
|
|
@@ -197,10 +222,16 @@ export function agentUpdateSchedule(id: NodeIdentity, canWrite: boolean, schedul
|
|
|
197
222
|
if (!node?.alias) return fail("target_node_not_found");
|
|
198
223
|
target = { node_id: node.node_id, alias: node.alias };
|
|
199
224
|
}
|
|
200
|
-
|
|
201
|
-
|
|
225
|
+
// 经授权改别人建的计划、且不改目标:不再要求本节点能给目标 send_task(每次执行仍按建计划者复查)。
|
|
226
|
+
// 改目标 / 改自己建的:照旧走 send_task 的判定。
|
|
227
|
+
const viaGrant = row.created_by_node_id !== id.nodeId;
|
|
228
|
+
if (!viaGrant || retarget) {
|
|
229
|
+
const denied = targetDenied(id, route, target);
|
|
230
|
+
if (denied) return denied;
|
|
231
|
+
}
|
|
202
232
|
try {
|
|
203
233
|
const patched = patchSchedule(row, { ...body, revision: body.revision ?? row.revision }, id.ownerUserId);
|
|
234
|
+
auditGrantMutation(id, row, retarget ? "update_retarget" : "update");
|
|
204
235
|
return { ok: true, schedule: decodeRowForAgent(patched) };
|
|
205
236
|
} catch (e) { return inputError(e); }
|
|
206
237
|
}
|
|
@@ -230,6 +261,7 @@ export function agentCancelSchedule(id: NodeIdentity, canWrite: boolean, schedul
|
|
|
230
261
|
const row = ownRow(id, scheduleId);
|
|
231
262
|
if (!isRow(row)) return row;
|
|
232
263
|
cancelSchedule(row);
|
|
264
|
+
auditGrantMutation(id, row, "cancel");
|
|
233
265
|
return { ok: true, status: "cancelled" };
|
|
234
266
|
}
|
|
235
267
|
|
|
@@ -240,10 +272,13 @@ export function agentRunScheduleNow(id: NodeIdentity, canWrite: boolean, schedul
|
|
|
240
272
|
const row = ownRow(id, scheduleId);
|
|
241
273
|
if (!isRow(row)) return row;
|
|
242
274
|
if (row.status === "cancelled") return fail("schedule_cancelled");
|
|
243
|
-
|
|
244
|
-
|
|
275
|
+
if (row.created_by_node_id === id.nodeId) {
|
|
276
|
+
const denied = targetDenied(id, route, { node_id: row.target_node_id, alias: row.target_alias });
|
|
277
|
+
if (denied) return denied;
|
|
278
|
+
}
|
|
245
279
|
try {
|
|
246
280
|
const result = dispatchScheduledOccurrence(row, new Date().toISOString(), false);
|
|
281
|
+
auditGrantMutation(id, row, "run_now");
|
|
247
282
|
const { event: _event, ...rest } = result;
|
|
248
283
|
return { ok: result.status !== "failed", ...rest };
|
|
249
284
|
} catch (e: any) {
|
|
@@ -636,6 +636,31 @@ describe("Hub scheduled task API and dispatcher", () => {
|
|
|
636
636
|
expect(runs.body.runs.length).toBeGreaterThanOrEqual(4);
|
|
637
637
|
});
|
|
638
638
|
|
|
639
|
+
test("purge deletes a stopped schedule with its runs; active ones and viewers are refused", async () => {
|
|
640
|
+
const q = `?network_id=${encodeURIComponent(networkId)}`;
|
|
641
|
+
const schedule = await createSchedule("purge me");
|
|
642
|
+
makeDue(schedule.schedule_id);
|
|
643
|
+
await runDueScheduledTasks(new Date());
|
|
644
|
+
expect(db.get<{ n: number }>("SELECT COUNT(*) AS n FROM scheduled_task_runs WHERE schedule_id = ?1", schedule.schedule_id)!.n).toBeGreaterThan(0);
|
|
645
|
+
// 还在跑的不让直接删:先 cancel。
|
|
646
|
+
const early = await api(ownerToken, `/api/scheduled-tasks/${schedule.schedule_id}/purge${q}`, { method: "POST", body: "{}" });
|
|
647
|
+
expect(early.status).toBe(409);
|
|
648
|
+
expect(early.body.error).toBe("schedule_not_stopped");
|
|
649
|
+
await api(ownerToken, `/api/scheduled-tasks/${schedule.schedule_id}/cancel${q}`, { method: "POST", body: "{}" });
|
|
650
|
+
// viewer 不能删(与 cancel 同一判据)。
|
|
651
|
+
const viewer = await api(viewerToken, `/api/scheduled-tasks/${schedule.schedule_id}/purge${q}`, { method: "POST", body: "{}" });
|
|
652
|
+
expect(viewer.status).toBe(403);
|
|
653
|
+
const purged = await api(ownerToken, `/api/scheduled-tasks/${schedule.schedule_id}/purge${q}`, { method: "POST", body: "{}" });
|
|
654
|
+
expect(purged.status).toBe(200);
|
|
655
|
+
expect(purged.body.status).toBe("purged");
|
|
656
|
+
expect((await api(ownerToken, `/api/scheduled-tasks/${schedule.schedule_id}${q}`)).status).toBe(404);
|
|
657
|
+
expect(db.get<{ n: number }>("SELECT COUNT(*) AS n FROM scheduled_task_runs WHERE schedule_id = ?1", schedule.schedule_id)!.n).toBe(0);
|
|
658
|
+
const listed = await api(ownerToken, `/api/scheduled-tasks${q}`);
|
|
659
|
+
expect(listed.body.schedules.some((r: any) => r.schedule_id === schedule.schedule_id)).toBe(false);
|
|
660
|
+
// 再删一次 = 404(行已经没了)。
|
|
661
|
+
expect((await api(ownerToken, `/api/scheduled-tasks/${schedule.schedule_id}/purge${q}`, { method: "POST", body: "{}" })).status).toBe(404);
|
|
662
|
+
});
|
|
663
|
+
|
|
639
664
|
test("a watcher can edit the schedule but cannot cancel it or change watchers", async () => {
|
|
640
665
|
const viewerId = db.get<{ user_id: string }>("SELECT user_id FROM network_members WHERE network_id = ?1 AND role = 'viewer'", networkId)!.user_id;
|
|
641
666
|
const schedule = await createSchedule(`watchers-${Date.now()}`);
|
package/src/scheduled-tasks.ts
CHANGED
|
@@ -6,6 +6,8 @@ import { sessionTaskOnDispatch } from "./session-task-on-dispatch.js";
|
|
|
6
6
|
import { TASK_CONTENT_MAX, sessionTaskPreview } from "./shared/task-content-limit.js";
|
|
7
7
|
import { assertNodeActive } from "./lifecycle-guard.js";
|
|
8
8
|
import { assertNodeHealthy } from "./node-health-guard.js";
|
|
9
|
+
import { neverConsumeGate, neverConsumedExpiryCounters, persistentNeverConsumedExpiries } from "./expiry-counters.js";
|
|
10
|
+
import { db as hubDb } from "./db.js";
|
|
9
11
|
import { nodeCanAcceptDispatch } from "./node-serviceability.js";
|
|
10
12
|
import { addNetworkScope, canRestWriteNetwork, singleNetworkId, type RestNetworkScope } from "./network-scope.js";
|
|
11
13
|
import { canMessageAgent, type AgentRef } from "./agent-access.js";
|
|
@@ -263,6 +265,15 @@ export function insertSchedule(networkId: string, createdBy: string | null, crea
|
|
|
263
265
|
}
|
|
264
266
|
|
|
265
267
|
/** Idempotent cancel (shared by REST DELETE / POST cancel and MCP schedule_cancel). */
|
|
268
|
+
/** 真删一条已停下的计划(见 purge 路由)。三张表一个事务。 */
|
|
269
|
+
export function purgeSchedule(scheduleId: string): void {
|
|
270
|
+
db.transaction(() => {
|
|
271
|
+
db.run("DELETE FROM scheduled_task_watchers WHERE schedule_id = ?1", [scheduleId]);
|
|
272
|
+
db.run("DELETE FROM scheduled_task_runs WHERE schedule_id = ?1", [scheduleId]);
|
|
273
|
+
db.run("DELETE FROM scheduled_tasks WHERE schedule_id = ?1", [scheduleId]);
|
|
274
|
+
});
|
|
275
|
+
}
|
|
276
|
+
|
|
266
277
|
export function cancelSchedule(row: ScheduledRow): void {
|
|
267
278
|
if (row.status === "cancelled") return;
|
|
268
279
|
db.run("UPDATE scheduled_tasks SET status = 'cancelled', next_run_at = NULL, backoff_streak = 0, backoff_effective_seconds = NULL, backoff_last_run_id = NULL, revision = revision + 1, updated_at = datetime('now') WHERE schedule_id = ?1", [row.schedule_id]);
|
|
@@ -649,6 +660,29 @@ export function dispatchScheduledOccurrence(row: ScheduledRow, scheduledFor: str
|
|
|
649
660
|
return;
|
|
650
661
|
}
|
|
651
662
|
|
|
663
|
+
// #4307/#4315 —— **排程派单也必须过这道闸**。
|
|
664
|
+
// 不然「某节点长期不消费」会被排程一遍遍喂任务:每一条都过期成 expired,
|
|
665
|
+
// 反过来把 never-consume 的计数顶得更高(实测 TMW微软欧 144/145 条 expired 全是
|
|
666
|
+
// 从未 consume 的排程任务)。REST 与 MCP 两个派单面本来就要同形,这里是第三个面。
|
|
667
|
+
// 判据完全相同:只看「最后一次成功回复之后」的过期;命中就 skip,不写任务行。
|
|
668
|
+
{
|
|
669
|
+
const gate = neverConsumeGate({
|
|
670
|
+
alias: node.alias,
|
|
671
|
+
counters: neverConsumedExpiryCounters(),
|
|
672
|
+
force: false,
|
|
673
|
+
forceAllowed: false,
|
|
674
|
+
persistent: persistentNeverConsumedExpiries(hubDb, node.alias, row.network_id),
|
|
675
|
+
});
|
|
676
|
+
if (!gate.ok) {
|
|
677
|
+
db.run(
|
|
678
|
+
"UPDATE scheduled_task_runs SET status = 'skipped', error_code = 'target_never_consumes', error_message = ?1, completed_at = datetime('now') WHERE run_id = ?2",
|
|
679
|
+
[gate.message.slice(0, 500), runId],
|
|
680
|
+
);
|
|
681
|
+
if (advanceSchedule) advance(row, scheduledFor, advanceAfter);
|
|
682
|
+
return;
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
|
|
652
686
|
const taskId = crypto.randomUUID();
|
|
653
687
|
// claude-code 裸节点的 node-server 上报 report_status 不带 node_id,它的 sessions 行
|
|
654
688
|
// node_id 永远是 NULL —— 只按 node_id 找会话,这类节点每一次都判成 queued、门铃不响,
|
|
@@ -920,7 +954,7 @@ export async function handleScheduledTaskRequest(ctx: ScheduledRequestContext):
|
|
|
920
954
|
}
|
|
921
955
|
}
|
|
922
956
|
|
|
923
|
-
const match = url.pathname.match(/^\/api\/scheduled-tasks\/([^/]+)(?:\/(runs|run-now|cancel))?$/);
|
|
957
|
+
const match = url.pathname.match(/^\/api\/scheduled-tasks\/([^/]+)(?:\/(runs|run-now|cancel|purge))?$/);
|
|
924
958
|
if (!match) return jsonError("not_found", 404);
|
|
925
959
|
const scheduleId = decodeURIComponent(match[1]);
|
|
926
960
|
const sub = match[2] || null;
|
|
@@ -935,7 +969,7 @@ export async function handleScheduledTaskRequest(ctx: ScheduledRequestContext):
|
|
|
935
969
|
const watcher = watchingSchedule(row.schedule_id, ctx.auth?.userId ?? null);
|
|
936
970
|
const writer = writeAllowed(ctx, row.network_id);
|
|
937
971
|
if (!writer && !watcher) return jsonError("permission_denied", 403);
|
|
938
|
-
if (!writer && (sub === "cancel" || (!sub && req.method === "DELETE"))) return jsonError("watcher_cannot_cancel", 403);
|
|
972
|
+
if (!writer && (sub === "cancel" || sub === "purge" || (!sub && req.method === "DELETE"))) return jsonError("watcher_cannot_cancel", 403);
|
|
939
973
|
if (!writer && sub === "run-now") return jsonError("watcher_cannot_run", 403);
|
|
940
974
|
|
|
941
975
|
if (sub === "run-now" && req.method === "POST") {
|
|
@@ -963,6 +997,16 @@ export async function handleScheduledTaskRequest(ctx: ScheduledRequestContext):
|
|
|
963
997
|
return Response.json({ ok: true, status: "cancelled" });
|
|
964
998
|
}
|
|
965
999
|
|
|
1000
|
+
// Purge(admin 2026-11-11「没有删除定时任务的功能」)—— 真删:计划行 + 执行记录 + 关注人一起删掉,
|
|
1001
|
+
// 列表里不再出现。只删已经停下的计划(cancelled / completed);还在跑的先 cancel 再 purge,
|
|
1002
|
+
// 避免一次误点把正在派发的计划连同历史一起抹掉。已派出去的 task 行不动(那是节点收件箱的历史)。
|
|
1003
|
+
// 不存在 = 404(上面 scopedSchedule 已判);重复 purge 的第二次也就是 404。
|
|
1004
|
+
if (sub === "purge" && (req.method === "POST" || req.method === "DELETE")) {
|
|
1005
|
+
if (row.status !== "cancelled" && row.status !== "completed") return jsonError("schedule_not_stopped", 409, { status: row.status });
|
|
1006
|
+
purgeSchedule(row.schedule_id);
|
|
1007
|
+
return Response.json({ ok: true, status: "purged", schedule_id: row.schedule_id });
|
|
1008
|
+
}
|
|
1009
|
+
|
|
966
1010
|
if (!sub && req.method === "PATCH") {
|
|
967
1011
|
let body: Record<string, unknown>;
|
|
968
1012
|
try { body = await bodyObject(req); } catch { return jsonError("invalid_json", 400); }
|
package/src/server.ts
CHANGED
|
@@ -15,6 +15,7 @@ import { statusAliasResolverRead } from "./status-alias-resolver.js";
|
|
|
15
15
|
import { readNodeHealth } from "./node-health-store.js";
|
|
16
16
|
import { wantsAllTools } from "./tool-audience.js";
|
|
17
17
|
import { assertNodeHealthy, degradedLayers } from "./node-health-guard.js";
|
|
18
|
+
import { GRANT_CAPABILITIES, grantsWithinManaged, listNodeGrants, parseNodeGrants, replaceNodeGrants } from "./node-grants.js";
|
|
18
19
|
import { auditDepartment, createDepartment, deleteDepartment, listDepartments, setAgentDepartment, setMemberDepartment, updateDepartment } from "./departments.js";
|
|
19
20
|
import { activeBinding, createdDaemon } from "./node-daemon-bindings.js";
|
|
20
21
|
import { countInFlightTasks } from "./node-in-flight-tasks.js";
|
|
@@ -56,13 +57,13 @@ import { getTaskAccessMode, isTaskScoped, listProjectGrants, replaceTaskGrants,
|
|
|
56
57
|
import { canMessageAgent, isAgentRestricted, visibleAgents, listAgentGrants, listGroupGrants, getAgentAccessMode, replaceAgentGrants, restrictedNetworkIds, usernameIsAgentAlias, listAgentGroups, createAgentGroup, updateAgentGroup, replaceAgentGroupMembers, deleteAgentGroup, usersGrantedGroup, listDepartmentGrants, departmentCoverage } from "./agent-access.js";
|
|
57
58
|
import { broadcastVerdict, dispatchVerdict, filterBroadcastByInbox, humanOnlyVerdict, inboxDenied, inboxSenderFromAuth, NODE_PERMISSION_MODES, nodeDecide, nodeIdentity, nodePermissionDeniedBody, nodePermissionsFlag, streamVerdict, writeVerdict, type InboxSender, type NodeIdentity, type NodePermissionMode, type Verdict } from "./node-permissions.js";
|
|
58
59
|
import { validateAvatarUrl } from "./avatar-validate.js";
|
|
59
|
-
import { narrowTags, parseStoredTags, validateScalarAttr } from "./node-attrs-validate.js";
|
|
60
|
+
import { narrowTags, parseStoredTags, validateDescription, validateScalarAttr } from "./node-attrs-validate.js";
|
|
60
61
|
import { daemonDefaultWorkdirRoot } from "./create-node-validate.js";
|
|
61
62
|
import { register, login, resolveToken, tokenRejection, isExpiredSessionToken, sessionIdleDays, listSessions, revokeSession, revokeOtherSessions, getUserNetworks, getUserAllNetworks, createNetwork, deleteNetwork, adminDeleteEmptyNetwork, renameNetwork, changePassword, issueUserToken, getUserTokenMeta, listTokens, createToken, revokeToken, getNetworkMembers, getNetworkHumans, getUserNetworkRole, addNetworkMember, adminCreateUser, listUsersWithMemberships, updateMemberRole, removeNetworkMember, createInvite, joinByInvite, createNetworkTokenForNode, type AuthUser } from "./auth.js";
|
|
62
63
|
import { abortRename, cleanupCommittedRenameSessions, commitRename, prepareRename, resolveCanonicalAlias } from "./rename.js";
|
|
63
64
|
import { sharedSendDedup, buildDuplicateSendPayload } from "./send_dedup.js";
|
|
64
65
|
import { clientRequestIdFromMeta, idempotentTaskId, idempotentTaskMatches, type StoredIdempotentTask } from "./task-idempotency.js";
|
|
65
|
-
import { getLoginClientIp, sharedLoginFailureLockout, sharedLoginIpRateLimiter } from "./auth_login_guard.js";
|
|
66
|
+
import { getLoginClientIp, normalizePeerIp, sharedLoginFailureLockout, sharedLoginIpRateLimiter } from "./auth_login_guard.js";
|
|
66
67
|
import {
|
|
67
68
|
FILE_ID_REGEX,
|
|
68
69
|
MAX_REQUEST_CONTENT_LENGTH,
|
|
@@ -108,6 +109,12 @@ import { startDueReminderTimer } from "./requirement-due-reminders.js";
|
|
|
108
109
|
import { clearNodeFromRequirements, handleRequirementsRequest } from "./requirements.js";
|
|
109
110
|
import { readHubProviders, putHubProvider, providerWriteStatus } from "./hub-provider-config.js";
|
|
110
111
|
import { readLastConfigUpdate } from "./node-config-last-update.js";
|
|
112
|
+
// #4495 —— 源目录 / 新建节点 / 复用已有 Session 的能力值。Hub 只认这几个**精确**字符串,
|
|
113
|
+
// 别的值一律不投影(daemon 上报的是自由 JSON,不能把任意串透给客户端当能力)。
|
|
114
|
+
import { SOURCE_DIRECTORY_CAPABILITY } from "./contracts/session-source-directory.js";
|
|
115
|
+
import { SOURCE_FORK_CAPABILITY } from "./contracts/session-source-transport.js";
|
|
116
|
+
import { SOURCE_DELIVERY_CAPABILITY } from "./contracts/session-source-delivery.js";
|
|
117
|
+
import { PROJECT_CREATE_CAPABILITY, SESSION_ATTACH_CAPABILITY } from "./contracts/session-project-create.js";
|
|
111
118
|
import { readTokenUsage, tokenUsageCoverage } from "./node-token-usage.js";
|
|
112
119
|
import { readBuildInfo } from "./build-info.js";
|
|
113
120
|
import { requestProviderApplication } from "./daemon-provider-snapshots.js";
|
|
@@ -218,7 +225,11 @@ const SERVER_VERSION_SOURCE = RESOLVED_VERSION.source;
|
|
|
218
225
|
// GET /api/dm/threads 的 group_threads;群对象带 viewer_can {manage, post},会话行带 last_message 预览,成员带 username / display_name。
|
|
219
226
|
// node_inbox_allowlist:收件白名单可用 —— PUT /api/nodes/:id/inbox-allowlist { senders },GET /api/nodes 每行带 inbox_allowlist,
|
|
220
227
|
// 被挡的派活回 reason=sender_not_allowed,广播回 inbox_skipped(有人被跳过时才出现,没人被跳过时回执与以前逐字节相同)。
|
|
221
|
-
|
|
228
|
+
// scheduled_task_purge:POST /api/scheduled-tasks/:id/purge 真删一条已停下(cancelled / completed)的计划,连执行记录一起删;
|
|
229
|
+
// 还在跑的回 409 schedule_not_stopped(先 cancel)。
|
|
230
|
+
// node_inbox_allowlist_dept:收件白名单认 dept:<department_id>(该部门及子部门里的节点和人)。
|
|
231
|
+
// node_grants:节点管理授权 GET/PUT /api/nodes/:id/grants(能力 schedules × 范围 network/department/node × read/edit)。
|
|
232
|
+
export const HUB_HEALTH_CAPABILITIES = ["status_node_id", "node_permission_mode", "chat_groups", "node_inbox_allowlist", "scheduled_task_purge", "node_inbox_allowlist_dept", "node_grants", "create_node_department"] as const;
|
|
222
233
|
|
|
223
234
|
// In-memory log ring buffer — last N lines streamed via /api/server-logs.
|
|
224
235
|
// Wraps console.log/info/warn/error so EVERY existing log call lands here
|
|
@@ -324,6 +335,28 @@ function requireAuth(req: Request, options: RequestTokenOptions = {}): Response
|
|
|
324
335
|
return Response.json({ error: "unauthorized", ...(tokenRejection(token) ?? {}) }, { status: 401 });
|
|
325
336
|
}
|
|
326
337
|
|
|
338
|
+
/** COMMHUB_ALLOWED_PEER_IPS(逗号分隔)。回环地址(127.0.0.0/8、::1)永远放行;拿不到对端地址时放行(不误伤)。 */
|
|
339
|
+
const ALLOWED_PEER_IPS: Set<string> | null = (() => {
|
|
340
|
+
const raw = process.env.COMMHUB_ALLOWED_PEER_IPS?.trim();
|
|
341
|
+
return raw ? new Set(raw.split(",").map(s => normalizePeerIp(s.trim())).filter(Boolean)) : null;
|
|
342
|
+
})();
|
|
343
|
+
export function peerAllowed(peer: string | null, allowed: Set<string> | null = ALLOWED_PEER_IPS): boolean {
|
|
344
|
+
if (!allowed) return true;
|
|
345
|
+
const ip = normalizePeerIp(peer);
|
|
346
|
+
if (!ip) return true;
|
|
347
|
+
if (ip === "::1" || ip.startsWith("127.")) return true;
|
|
348
|
+
return allowed.has(ip);
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/**
|
|
352
|
+
* COMMHUB_REGISTRATION=closed —— 关掉公开注册(POST /api/auth/register 回 403 registration_closed)。
|
|
353
|
+
* 不设 / 其它值 = 开放(旧行为)。第一个用户(自动成为 admin)不受影响:库里还没有用户时照常放行。
|
|
354
|
+
*/
|
|
355
|
+
function registrationClosed(): boolean {
|
|
356
|
+
if ((process.env.COMMHUB_REGISTRATION ?? "").trim().toLowerCase() !== "closed") return false;
|
|
357
|
+
return !!db.get<{ ok: number }>("SELECT 1 AS ok FROM users LIMIT 1");
|
|
358
|
+
}
|
|
359
|
+
|
|
327
360
|
function getClientIP(req: Request, server?: any): string {
|
|
328
361
|
const direct = server?.requestIP?.(req)?.address;
|
|
329
362
|
if (direct) return direct;
|
|
@@ -2060,6 +2093,12 @@ return Bun.serve({
|
|
|
2060
2093
|
error: (err) => buildServeErrorResponse(err),
|
|
2061
2094
|
|
|
2062
2095
|
async fetch(req, server) {
|
|
2096
|
+
// 2026-11-11 安全排查 —— COMMHUB_ALLOWED_PEER_IPS:Hub 端口只接这些对端(外加本机回环)。
|
|
2097
|
+
// 生产 :9200 直接暴露在公网,但真正的来路只有本机(frp、本机节点)和 https 反代那台机器;
|
|
2098
|
+
// 没有云安全组权限时,在 Hub 里把其它来源挡在门外。不设 = 不限制(旧行为)。
|
|
2099
|
+
if (!peerAllowed(server?.requestIP?.(req)?.address ?? null)) {
|
|
2100
|
+
return new Response(JSON.stringify({ ok: false, error: "peer_not_allowed" }), { status: 403, headers: { "Content-Type": "application/json", Connection: "close" } });
|
|
2101
|
+
}
|
|
2063
2102
|
// 2026-09-16 —— 所有 JSON/文本响应在客户端要求时 gzip(见 http-gzip.ts);SSE/流式/二进制原样。
|
|
2064
2103
|
// 2026-09-30 —— 每个请求的路由形状 + 耗时进内存环(route-timing.ts),GET /api/stats/routes 看谁在吃 CPU。
|
|
2065
2104
|
return recordRouteTiming(req, performance.now(), await maybeGzipResponse(req, explainExpiredSession(req, await (async (): Promise<Response | undefined> => {
|
|
@@ -2391,7 +2430,9 @@ return Bun.serve({
|
|
|
2391
2430
|
// 现已移除;命中时按未知路径处理(404),不再保留兼容壳。
|
|
2392
2431
|
// ── V3: Auth endpoints (public) ──
|
|
2393
2432
|
if (url.pathname === "/api/auth/register" && req.method === "POST") {
|
|
2394
|
-
|
|
2433
|
+
// 与登录同一口径(最后一跳 + COMMHUB_TRUSTED_PROXY_IPS):原来取第一跳,客户端随便写就能换桶。
|
|
2434
|
+
const clientIP = getLoginClientIp(req, server?.requestIP?.(req)?.address ?? null);
|
|
2435
|
+
if (registrationClosed()) return withCors(req, Response.json({ ok: false, error: "registration_closed", message: "This Hub does not accept new sign-ups. Ask an admin for an invite." }, { status: 403 }));
|
|
2395
2436
|
if (!checkRateLimit(clientIP, 30)) {
|
|
2396
2437
|
noteRegisterRateLimited(clientIP);
|
|
2397
2438
|
return withCors(req, Response.json({ ok: false, error: "too many requests, try again later" }, { status: 429 }));
|
|
@@ -2407,7 +2448,7 @@ return Bun.serve({
|
|
|
2407
2448
|
}
|
|
2408
2449
|
|
|
2409
2450
|
if (url.pathname === "/api/auth/login" && req.method === "POST") {
|
|
2410
|
-
const clientIP = getLoginClientIp(req);
|
|
2451
|
+
const clientIP = getLoginClientIp(req, server?.requestIP?.(req)?.address ?? null);
|
|
2411
2452
|
const ipRate = sharedLoginIpRateLimiter.check(clientIP || "unknown");
|
|
2412
2453
|
if (!ipRate.allowed) {
|
|
2413
2454
|
logAudit(null, null, "login_rate_limited", "auth", undefined, clientIP);
|
|
@@ -4361,6 +4402,42 @@ return Bun.serve({
|
|
|
4361
4402
|
logAudit(restAuth.userId, restAuth.username, "node_peer_allowlist_changed", "node", node2.node_id, JSON.stringify({ from: node2.peer_allowlist, to: nextValue }), getClientIP(req), node2.network_id);
|
|
4362
4403
|
return withCors(req, Response.json({ ok: true, node_id: node2.node_id, peers: peers.length ? peers : null }));
|
|
4363
4404
|
}
|
|
4405
|
+
// 节点管理授权(node-grants.ts):GET / PUT /api/nodes/:id/grants { grants: [{capability, scope_kind, scope_id, level}] }
|
|
4406
|
+
// 读:本网络成员。写:网络 owner / admin、Hub 管理员可授任意范围;部门负责人只能授自己负责子树里的
|
|
4407
|
+
// department / node 范围。**节点主人不行**(否则任何成员都能给自己的节点授全网的权)。PUT 是整份替换,[] 清空。
|
|
4408
|
+
const nodeGrantsMatch = url.pathname.match(/^\/api\/nodes\/([^/]+)\/grants$/);
|
|
4409
|
+
if (nodeGrantsMatch && (req.method === "GET" || req.method === "PUT")) {
|
|
4410
|
+
if (!restAuth) return withCors(req, Response.json({ ok: false, error: "auth required" }, { status: 401 }));
|
|
4411
|
+
if (restAuth.networkId) return userTokenRequired(req);
|
|
4412
|
+
const ref = decodeURIComponent(nodeGrantsMatch[1]);
|
|
4413
|
+
const gnode = db.get<{ node_id: string; network_id: string | null }>("SELECT node_id, network_id FROM nodes WHERE node_id = ?1", ref);
|
|
4414
|
+
const grole = gnode?.network_id ? getUserNetworkRole(restAuth.userId, gnode.network_id) : null;
|
|
4415
|
+
if (!gnode || !gnode.network_id || (!grole && !isAdmin)) return withCors(req, Response.json({ ok: false, error: "node_not_found" }, { status: 404 }));
|
|
4416
|
+
if (req.method === "GET") {
|
|
4417
|
+
return withCors(req, Response.json({ ok: true, node_id: gnode.node_id, grants: listNodeGrants(gnode.network_id, gnode.node_id), capabilities: GRANT_CAPABILITIES }));
|
|
4418
|
+
}
|
|
4419
|
+
let body: any;
|
|
4420
|
+
try { body = await req.json(); } catch { return withCors(req, Response.json({ ok: false, error: "invalid_json" }, { status: 400 })); }
|
|
4421
|
+
const parsed = parseNodeGrants(gnode.network_id, body?.grants);
|
|
4422
|
+
if (!parsed.ok) return withCors(req, Response.json(parsed, { status: parsed.error.endsWith("_not_found") ? 404 : 400 }));
|
|
4423
|
+
const fullAdmin = isAdmin || grole === "owner" || grole === "admin";
|
|
4424
|
+
if (!fullAdmin) {
|
|
4425
|
+
const managed = new Set(managedDepartmentIds(gnode.network_id, restAuth.userId).flatMap(d => [...departmentSubtree(gnode.network_id!, d)]));
|
|
4426
|
+
const before = listNodeGrants(gnode.network_id, gnode.node_id);
|
|
4427
|
+
// 负责人改的是整份名单:名单里不在他管辖内的旧授权必须原样保留,新增 / 删除的都得在他的子树里。
|
|
4428
|
+
const outside = (g: { scope_kind: string; scope_id: string }) => !grantsWithinManaged(gnode.network_id!, [g as any], managed);
|
|
4429
|
+
const keptOutside = before.filter(outside).every(b => parsed.grants.some(g => g.capability === b.capability && g.scope_kind === b.scope_kind && g.scope_id === b.scope_id && g.level === b.level));
|
|
4430
|
+
const addedOutside = parsed.grants.filter(outside).some(g => !before.some(b => b.capability === g.capability && b.scope_kind === g.scope_kind && b.scope_id === g.scope_id && b.level === g.level));
|
|
4431
|
+
if (!managed.size || !keptOutside || addedOutside) {
|
|
4432
|
+
return withCors(req, Response.json({ ok: false, error: "permission_denied", message: "only network owners/admins can grant network-wide access; department heads can grant within the departments they lead" }, { status: 403 }));
|
|
4433
|
+
}
|
|
4434
|
+
}
|
|
4435
|
+
const before = listNodeGrants(gnode.network_id, gnode.node_id);
|
|
4436
|
+
replaceNodeGrants(gnode.network_id, gnode.node_id, parsed.grants, restAuth.userId);
|
|
4437
|
+
logAudit(restAuth.userId, restAuth.username, "node_grants_changed", "node", gnode.node_id,
|
|
4438
|
+
JSON.stringify({ from: before.map(({ capability, scope_kind, scope_id, level }) => ({ capability, scope_kind, scope_id, level })), to: parsed.grants }), getClientIP(req), gnode.network_id);
|
|
4439
|
+
return withCors(req, Response.json({ ok: true, node_id: gnode.node_id, grants: listNodeGrants(gnode.network_id, gnode.node_id) }));
|
|
4440
|
+
}
|
|
4364
4441
|
// 收件白名单:PUT /api/nodes/:id/inbox-allowlist { senders: string[] | null }
|
|
4365
4442
|
// 与 peer-allowlist 同一套授权、审计与空数组语义(拒收 [],清空请传 null)。
|
|
4366
4443
|
// 条目语法与发件人匹配规则见 node-permissions.ts「收件白名单」。
|
|
@@ -6544,6 +6621,9 @@ return Bun.serve({
|
|
|
6544
6621
|
const lastUpdate = readLastConfigUpdate(
|
|
6545
6622
|
(sql: string, ...params: any[]) => (db.get as any)(sql, ...params),
|
|
6546
6623
|
node.node_id,
|
|
6624
|
+
// #4499 —— 排队后被应用的那种下发:ack 当时是 rejected/variant_busy,
|
|
6625
|
+
// 节点随后把档位改过去了。用「当前回读的档位」判断它到底生效了没有。
|
|
6626
|
+
{ currentVariant: typeof snapshot.modelVariant === "string" ? snapshot.modelVariant : null },
|
|
6547
6627
|
);
|
|
6548
6628
|
return withCors(req, Response.json({
|
|
6549
6629
|
ok: true,
|
|
@@ -6604,7 +6684,7 @@ return Bun.serve({
|
|
|
6604
6684
|
}
|
|
6605
6685
|
const ref = decodeURIComponent(nodeAttrsMatch[1]);
|
|
6606
6686
|
const params: any[] = [ref, ref, ref];
|
|
6607
|
-
let sql = "SELECT node_id, alias, network_id, display_name, team, tags, attrs_revision FROM nodes WHERE (node_id = ?1 OR node_name = ?2 OR alias = ?3)";
|
|
6687
|
+
let sql = "SELECT node_id, alias, network_id, display_name, team, tags, description, attrs_revision FROM nodes WHERE (node_id = ?1 OR node_name = ?2 OR alias = ?3)";
|
|
6608
6688
|
sql = addNetworkScope(sql, params, restScope);
|
|
6609
6689
|
sql += " ORDER BY updated_at DESC LIMIT 1";
|
|
6610
6690
|
const node = db.get<any>(sql, ...params);
|
|
@@ -6647,6 +6727,20 @@ return Bun.serve({
|
|
|
6647
6727
|
return withCors(req, Response.json({ ok: false, error: "invalid_team", reason: nextTeam.reason }, { status: 400 }));
|
|
6648
6728
|
}
|
|
6649
6729
|
const nextTags = "tags" in attrsBody ? narrowTags(attrsBody.tags) : null;
|
|
6730
|
+
// 职责介绍(多行,≤ 1000 字);类型错 → 400,和 display_name 同一姿态。
|
|
6731
|
+
const nextDescription = "description" in attrsBody ? validateDescription(attrsBody.description) : null;
|
|
6732
|
+
if (nextDescription && !nextDescription.ok) {
|
|
6733
|
+
return withCors(req, Response.json({ ok: false, error: "invalid_description", reason: nextDescription.reason }, { status: 400 }));
|
|
6734
|
+
}
|
|
6735
|
+
// 职责介绍是节点对外的「名片」:节点令牌只许写**自己的**,不看 node-permissions 开关(那个开关在 off / log 时会放行
|
|
6736
|
+
// 「写别的节点」—— 对展示名还算无害,对名片就是冒名)。人(用户令牌)照旧按网络写权限。
|
|
6737
|
+
if (nextDescription && restAuth?.networkId) {
|
|
6738
|
+
const caller = nodeIdentity(restAuth.tokenId, restAuth.networkId);
|
|
6739
|
+
const self = !!caller && ((!!caller.nodeId && caller.nodeId === node.node_id) || (!!node.alias && caller.aliases.includes(node.alias)));
|
|
6740
|
+
if (!self) {
|
|
6741
|
+
return withCors(req, Response.json({ ok: false, error: "description_self_only", message: "a node may only edit its own description; ask a person to edit another node's" }, { status: 403 }));
|
|
6742
|
+
}
|
|
6743
|
+
}
|
|
6650
6744
|
|
|
6651
6745
|
// Only the supplied fields move; the rest keep their stored value.
|
|
6652
6746
|
const sets: string[] = [];
|
|
@@ -6654,6 +6748,7 @@ return Bun.serve({
|
|
|
6654
6748
|
if (nextDisplay) { sets.push(`display_name = ?${vals.length + 1}`); vals.push(nextDisplay.value); }
|
|
6655
6749
|
if (nextTeam) { sets.push(`team = ?${vals.length + 1}`); vals.push(nextTeam.value); }
|
|
6656
6750
|
if (nextTags) { sets.push(`tags = ?${vals.length + 1}`); vals.push(JSON.stringify(nextTags)); }
|
|
6751
|
+
if (nextDescription) { sets.push(`description = ?${vals.length + 1}`); vals.push(nextDescription.value); }
|
|
6657
6752
|
// A no-op patch still bumps the revision: the caller observed a state
|
|
6658
6753
|
// and asserted it, so honouring the CAS keeps client counters in step.
|
|
6659
6754
|
sets.push(`attrs_revision = ?${vals.length + 1}`); vals.push(currentRev + 1);
|
|
@@ -6676,10 +6771,10 @@ return Bun.serve({
|
|
|
6676
6771
|
}, { status: 409 }));
|
|
6677
6772
|
}
|
|
6678
6773
|
logAudit(restAuth?.userId ?? null, restAuth?.username ?? null, "node_attrs_updated", "node", node.node_id,
|
|
6679
|
-
JSON.stringify({ display_name: nextDisplay?.value ?? undefined, team: nextTeam?.value ?? undefined, tags: nextTags ?? undefined }),
|
|
6774
|
+
JSON.stringify({ display_name: nextDisplay?.value ?? undefined, team: nextTeam?.value ?? undefined, tags: nextTags ?? undefined, description_changed: nextDescription ? true : undefined }),
|
|
6680
6775
|
undefined, nodeNetId ?? undefined);
|
|
6681
6776
|
const after = db.get<any>(
|
|
6682
|
-
"SELECT display_name, team, tags, attrs_revision FROM nodes WHERE node_id = ?1", node.node_id);
|
|
6777
|
+
"SELECT display_name, team, tags, description, attrs_revision FROM nodes WHERE node_id = ?1", node.node_id);
|
|
6683
6778
|
return withCors(req, Response.json({
|
|
6684
6779
|
ok: true,
|
|
6685
6780
|
node_id: node.node_id,
|
|
@@ -6687,6 +6782,7 @@ return Bun.serve({
|
|
|
6687
6782
|
display_name: after?.display_name ?? null,
|
|
6688
6783
|
team: after?.team ?? null,
|
|
6689
6784
|
tags: parseStoredTags(after?.tags),
|
|
6785
|
+
description: after?.description ?? null,
|
|
6690
6786
|
attrs_revision: Number(after?.attrs_revision ?? currentRev + 1),
|
|
6691
6787
|
}));
|
|
6692
6788
|
}
|
|
@@ -6853,6 +6949,8 @@ return Bun.serve({
|
|
|
6853
6949
|
// 而这一格存在的全部意义就是让人分辨新鲜和陈旧。
|
|
6854
6950
|
let snapObservedMsAgo: number | undefined;
|
|
6855
6951
|
let snapReadiness: ReturnType<typeof sanitizeRuntimeReadiness>;
|
|
6952
|
+
// #4495 —— 源能力,只在 daemon 真的按契约上报时才有键。
|
|
6953
|
+
const snapCaps: Record<string, string> = {};
|
|
6856
6954
|
if (r.config_snapshot) {
|
|
6857
6955
|
try {
|
|
6858
6956
|
const parsed = typeof r.config_snapshot === "string" ? JSON.parse(r.config_snapshot) : r.config_snapshot;
|
|
@@ -6874,14 +6972,28 @@ return Bun.serve({
|
|
|
6874
6972
|
}
|
|
6875
6973
|
// #622 —— 逐 runtime 就绪度;旧 daemon 不报 ⇒ undefined ⇒ 响应里没有这个键。
|
|
6876
6974
|
snapReadiness = sanitizeRuntimeReadiness(caps?.runtime_readiness);
|
|
6975
|
+
// #4495 —— 这五条以前**只存在 nodes.config_snapshot 里,没有任何 REST 出口**:
|
|
6976
|
+
// 客户端想知道「这台 daemon 能不能列已有项目 / 复用已有 Session」只能靠猜
|
|
6977
|
+
// (app 里 NodeSourcePalette 干脆写死 hasProjectCreateCapability: true)。
|
|
6978
|
+
// 现在按精确能力值投影出来;没报 / 报的值不认识 ⇒ 键不出现(与 can_create_nodes 同一套兼容口径)。
|
|
6979
|
+
for (const [key, want] of [
|
|
6980
|
+
["source_directory_read", SOURCE_DIRECTORY_CAPABILITY],
|
|
6981
|
+
["project_new_session", PROJECT_CREATE_CAPABILITY],
|
|
6982
|
+
["session_attach", SESSION_ATTACH_CAPABILITY],
|
|
6983
|
+
["source_fork_transport", SOURCE_FORK_CAPABILITY],
|
|
6984
|
+
["source_node_delivery", SOURCE_DELIVERY_CAPABILITY],
|
|
6985
|
+
] as const) {
|
|
6986
|
+
const v = (caps as Record<string, unknown> | undefined)?.[key];
|
|
6987
|
+
if (typeof v === "string" && v === want) snapCaps[key] = v;
|
|
6988
|
+
}
|
|
6877
6989
|
} catch { /* malformed */ }
|
|
6878
6990
|
}
|
|
6879
6991
|
return { row: r, role: snapRole, canCreate: snapCanCreate, blockedReason: snapBlockedReason,
|
|
6880
6992
|
observedMsAgo: snapObservedMsAgo, readiness: snapReadiness, adoptCapable: snapAdoptCapable,
|
|
6881
|
-
adoptionDiscovery: snapAdoptionDiscovery };
|
|
6993
|
+
adoptionDiscovery: snapAdoptionDiscovery, caps: snapCaps };
|
|
6882
6994
|
})
|
|
6883
6995
|
.filter(({ role }) => role === "host_supervisor")
|
|
6884
|
-
.map(({ row: r, canCreate, blockedReason, observedMsAgo, readiness, adoptCapable, adoptionDiscovery }) => {
|
|
6996
|
+
.map(({ row: r, canCreate, blockedReason, observedMsAgo, readiness, adoptCapable, adoptionDiscovery, caps }) => {
|
|
6885
6997
|
let online = false;
|
|
6886
6998
|
let lastSeenAt: string | null = null;
|
|
6887
6999
|
if (r.session_last_seen) {
|
|
@@ -6920,6 +7032,8 @@ return Bun.serve({
|
|
|
6920
7032
|
runtimes_supported: runtimes,
|
|
6921
7033
|
allowed_secret_keys: secrets,
|
|
6922
7034
|
host_telemetry: telemetry,
|
|
7035
|
+
// #4495 —— 没上报就不出现这些键(与 can_create_nodes 的「不是 false,是 undefined」同一口径)。
|
|
7036
|
+
...caps,
|
|
6923
7037
|
};
|
|
6924
7038
|
// #973 — only when the daemon actually reported one (see the SQL comment).
|
|
6925
7039
|
const reportedVersion = (r as unknown as { reported_version?: string | null }).reported_version;
|
|
@@ -6994,7 +7108,7 @@ return Bun.serve({
|
|
|
6994
7108
|
config_path, channels, server, hostname,
|
|
6995
7109
|
network_id, created_at, updated_at,
|
|
6996
7110
|
config_snapshot, lifecycle_state, avatar_url,
|
|
6997
|
-
display_name, team, tags, attrs_revision, permission_mode, owner_user_id,
|
|
7111
|
+
display_name, team, tags, description, attrs_revision, permission_mode, owner_user_id,
|
|
6998
7112
|
department_id, peer_allowlist, tool_allowlist, rest_allowlist, inbox_allowlist
|
|
6999
7113
|
FROM nodes WHERE 1=1`;
|
|
7000
7114
|
const params: any[] = [];
|
|
@@ -7149,6 +7263,7 @@ return Bun.serve({
|
|
|
7149
7263
|
let opencodeCatalog: string[] | null = null;
|
|
7150
7264
|
// null = daemon 没报采集时刻(不是「很久以前」,也不是「刚刚」)
|
|
7151
7265
|
let opencodeCatalogSeenAt: string | null = null;
|
|
7266
|
+
let opencodeCatalogVariants: string[] | null = null;
|
|
7152
7267
|
let opencodeGeneration: "v1" | "v2" | null = null;
|
|
7153
7268
|
let opencodeMode: string | null = null;
|
|
7154
7269
|
let opencodeServer: string | null = null;
|
|
@@ -7182,6 +7297,11 @@ return Bun.serve({
|
|
|
7182
7297
|
const seen = parsed?.opencode_catalog_seen_at;
|
|
7183
7298
|
opencodeCatalogSeenAt =
|
|
7184
7299
|
typeof seen === "string" && seen.length > 0 && seen.length <= 40 ? seen : null;
|
|
7300
|
+
// admin 2026-11-11 —— 每个模型的思考档位(`provider/model=a,b,c`),只做投影。
|
|
7301
|
+
const rawVariants = parsed?.opencode_catalog_variants;
|
|
7302
|
+
if (Array.isArray(rawVariants) && rawVariants.every((v: unknown) => typeof v === "string" && v.length <= 600)) {
|
|
7303
|
+
opencodeCatalogVariants = rawVariants.slice(0, 400);
|
|
7304
|
+
}
|
|
7185
7305
|
}
|
|
7186
7306
|
// #2293 —— 客户端「Runtime · V2」和「OpenCode Server」两行要的正是快照里这三格标量。
|
|
7187
7307
|
// PR #1092 之前从 `node.config_snapshot` 读,但这个端点**刻意不带整个快照**
|
|
@@ -7233,6 +7353,7 @@ return Bun.serve({
|
|
|
7233
7353
|
opencode_agents_seen_at: opencodeAgentsSeenAt,
|
|
7234
7354
|
// 见上:null 表示 daemon 未上报;非 null 是它自己给的采集时刻
|
|
7235
7355
|
opencode_catalog_seen_at: opencodeCatalogSeenAt,
|
|
7356
|
+
opencode_catalog_variants: opencodeCatalogVariants,
|
|
7236
7357
|
opencode_generation: opencodeGeneration,
|
|
7237
7358
|
opencode_mode: opencodeMode,
|
|
7238
7359
|
opencode_server: opencodeServer,
|