merge: fix/q-inline-handling
Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Cxwgnn2pbzQ7rXv3rq7fei # Conflicts: # apps/server/src/modules/sources-identity/service/episode-resolution.ts
This commit is contained in:
commit
c465b533fd
80 files changed
+2766
-1016
No files matched your search
@@ -14,6 +14,7 @@ import { previewPolicy, publishRevision } from "./routes/rules.ts";
|
||||
import { evaluateAcquisition, publishedAcquisitionPolicies } from "./services/acquisition.ts";
|
||||
import { type AoDeps, enqueueTracked, ensureTaskRow, markTask } from "./services/common.ts";
|
||||
import { type FrozenPlan, planImport } from "./services/organize.ts";
|
||||
import { assignOrganizeIdentity, OrganizeDecisionError } from "./services/takeover.ts";
|
||||
import { errMessage, hashJson, jsonb, toApi, toApiList } from "./util.ts";
|
||||
|
||||
// 本模块领域的能力处理器(规格一律取 contracts):
|
||||
@@ -591,6 +592,28 @@ export function registerAoCapabilities(registry: CapabilityRegistry, deps: () =>
|
||||
};
|
||||
});
|
||||
|
||||
// 整理时没识别出作品:智能体查到作品后指定,随即重新整理(授权见 agent/authorize.ts:只放行本事项的识别会话或用户对话)
|
||||
registry.register(capabilitySpec("organize.assign_identity"), async (input, ctx) => {
|
||||
if (!input.mediaEntityId && !input.tmdb)
|
||||
throw new CapabilityError("invalid_input", "需要 mediaEntityId 或 tmdb(类型 + ID)");
|
||||
try {
|
||||
return await assignOrganizeIdentity(
|
||||
deps(),
|
||||
input.decisionId,
|
||||
input.mediaEntityId ? { mediaEntityId: input.mediaEntityId } : { tmdb: input.tmdb },
|
||||
{ type: ctx.source === "web" ? "user" : "agent", id: ctx.agentRunId ?? ctx.actorId },
|
||||
input.reasons.join(";"),
|
||||
);
|
||||
} catch (e) {
|
||||
if (e instanceof OrganizeDecisionError)
|
||||
throw new CapabilityError(
|
||||
e.code === "bad_request" ? "invalid_input" : e.code === "not_found" ? "not_found" : "conflict",
|
||||
e.message,
|
||||
);
|
||||
throw e;
|
||||
}
|
||||
});
|
||||
|
||||
registry.register(capabilitySpec("organize.execute"), async (input, ctx) => {
|
||||
const d = deps();
|
||||
const db = d.ctx.db;
|
||||
|
||||
@@ -1,17 +1,68 @@
|
||||
import { Dashboard, type DecisionKind, type SlotStatusCounts } from "@umt/contracts";
|
||||
import { Api, Dashboard, type Decision, type DecisionKind, type SlotStatusCounts } from "@umt/contracts";
|
||||
import { sql } from "@umt/db";
|
||||
import type { ModuleApp } from "../../types.ts";
|
||||
import type { AoDeps } from "../services/common.ts";
|
||||
import { cleanupCandidates } from "../services/downloads.ts";
|
||||
import { attentionSql } from "../services/organize-records.ts";
|
||||
import { decideVolume, loadVolumes, usedPercent, volumeThresholds } from "../services/volumes.ts";
|
||||
import { startOfDay } from "../util.ts";
|
||||
import { startOfDay, toApiList } from "../util.ts";
|
||||
import { mount } from "./helpers.ts";
|
||||
|
||||
// 首页六区块(REQ §13.4.3):只读投影,统计未知时给 null 并在 notes 说明。
|
||||
|
||||
const iso = (v: Date | null | undefined) => (v ? v.toISOString() : null);
|
||||
|
||||
/** 需要你批准的智能体操作:会话里的审批 / 方案选择、计划审批(整理记录上的审批在整理记录里处理)、原站页面等你接手 */
|
||||
const APPROVAL_SQL = sql<boolean>`(subject_type = 'agent_run'
|
||||
or (kind = 'approval_required' and coalesce(subject_type, '') <> 'organization_record')
|
||||
or dedupe_key like 'browser.waiting:%')`;
|
||||
/** 系统健康:站点不可达、下载器离线、下载目录读不到容量、磁盘空间不足、媒体库目录离线(恢复后自动关闭) */
|
||||
const HEALTH_SQL = sql<boolean>`(kind in ('source_unreachable', 'downloader_offline', 'cache_volume_unknown', 'space_insufficient')
|
||||
or dedupe_key like 'library_root_offline:%')`;
|
||||
const OPEN_SQL = sql<boolean>`status in ('open', 'investigating', 'awaiting_user')`;
|
||||
const ATTENTION_ITEMS = 20;
|
||||
|
||||
export function registerDashboardRoutes(app: ModuleApp, d: AoDeps) {
|
||||
// 铃铛 / 首页 / 运行状态共用的「需要关注」汇总(口径见 contracts AttentionSummary)
|
||||
mount(
|
||||
app,
|
||||
Api.attention.summary,
|
||||
async () => {
|
||||
const db = d.ctx.db;
|
||||
const group = async (where: typeof APPROVAL_SQL) => {
|
||||
const [items, total] = await Promise.all([
|
||||
db
|
||||
.selectFrom("decision")
|
||||
.selectAll()
|
||||
.where(OPEN_SQL)
|
||||
.where(where)
|
||||
.orderBy("created_at", "desc")
|
||||
.limit(ATTENTION_ITEMS)
|
||||
.execute(),
|
||||
db
|
||||
.selectFrom("decision")
|
||||
.select((eb) => eb.fn.countAll<string>().as("n"))
|
||||
.where(OPEN_SQL)
|
||||
.where(where)
|
||||
.executeTakeFirst(),
|
||||
]);
|
||||
return { total: Number(total?.n ?? 0), items: toApiList<Decision>(items) };
|
||||
};
|
||||
const [organize, approvals, health] = await Promise.all([
|
||||
db
|
||||
.selectFrom("organization_record")
|
||||
.select((eb) => eb.fn.countAll<string>().as("n"))
|
||||
.where("action", "in", ["copy", "move", "in_place", "hardlink"])
|
||||
.where(attentionSql())
|
||||
.executeTakeFirst(),
|
||||
group(APPROVAL_SQL),
|
||||
group(HEALTH_SQL),
|
||||
]);
|
||||
return { organize: Number(organize?.n ?? 0), approvals, health };
|
||||
},
|
||||
{ tag: "dashboard" },
|
||||
);
|
||||
|
||||
mount(
|
||||
app,
|
||||
{
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
type SourceGuard,
|
||||
sourceGuard,
|
||||
} from "../services/organize-guard.ts";
|
||||
import { attentionSql } from "../services/organize-records.ts";
|
||||
import { actorOf, errMessage, hashJson, jsonb, notFound } from "../util.ts";
|
||||
import { mount, paginate } from "./helpers.ts";
|
||||
|
||||
@@ -50,7 +51,14 @@ export function registerOrganizationRoutes(app: ModuleApp, d: AoDeps) {
|
||||
query,
|
||||
).execute();
|
||||
const n = (s: string) => Number(rows.find((r) => r.status === s)?.n ?? 0);
|
||||
const att = await recordFilters(
|
||||
db()
|
||||
.selectFrom("organization_record")
|
||||
.select((eb) => eb.fn.countAll<string>().as("n")),
|
||||
{ ...query, attention: true },
|
||||
).executeTakeFirst();
|
||||
return {
|
||||
attention: Number(att?.n ?? 0),
|
||||
total: rows.reduce((a, r) => a + Number(r.n), 0),
|
||||
succeeded: n("succeeded"),
|
||||
partial: n("partial"),
|
||||
@@ -102,6 +110,79 @@ export function registerOrganizationRoutes(app: ModuleApp, d: AoDeps) {
|
||||
{ tag: TAG },
|
||||
);
|
||||
|
||||
// 忽略:这条记录不再算需要处理;关联的未关闭事项一并关闭(dismissed)
|
||||
mount(
|
||||
app,
|
||||
Api.organization.dismissAttention,
|
||||
async (c, { params }) => {
|
||||
const by = actorOf(c);
|
||||
const rec = await db()
|
||||
.transaction()
|
||||
.execute(async (trx) => {
|
||||
const r = await trx
|
||||
.updateTable("organization_record")
|
||||
.set({ attention_cleared_at: d.ports.now() })
|
||||
.where("id", "=", params.id)
|
||||
.returningAll()
|
||||
.executeTakeFirst();
|
||||
if (!r) return null;
|
||||
const closed = await trx
|
||||
.updateTable("decision")
|
||||
.set({
|
||||
status: "dismissed",
|
||||
resolution: jsonb({ optionKey: null, note: "在整理记录里忽略", by }),
|
||||
resolved_by: by,
|
||||
resolved_at: d.ports.now(),
|
||||
})
|
||||
.where("subject_type", "=", "organization_record")
|
||||
.where("subject_id", "=", params.id)
|
||||
.where("status", "in", ["open", "investigating", "awaiting_user"])
|
||||
.returning("id")
|
||||
.execute();
|
||||
for (const x of closed)
|
||||
await d.ctx.outbox.emit(
|
||||
trx,
|
||||
"decision.updated",
|
||||
{ decisionId: x.id, status: "dismissed" },
|
||||
{ idempotencyKey: `decision.updated:${x.id}:dismissed` },
|
||||
);
|
||||
return r;
|
||||
});
|
||||
if (!rec) notFound("整理记录");
|
||||
await audit(d, by, "organize.attention_dismissed", { recordId: params.id });
|
||||
return (await loadRecordsPublic(db(), [rec!], false))[0]!;
|
||||
},
|
||||
{ tag: TAG },
|
||||
);
|
||||
|
||||
// 让智能体识别:没识别出作品的记录入队一次识别会话(agent 模块 resolveDecision trigger=identify),认出来自动重新整理
|
||||
mount(
|
||||
app,
|
||||
Api.organization.agentIdentify,
|
||||
async (_c, { params }) => {
|
||||
const dec = await db()
|
||||
.selectFrom("decision")
|
||||
.select(["id", "status", "evidence"])
|
||||
.where("subject_type", "=", "organization_record")
|
||||
.where("subject_id", "=", params.id)
|
||||
.where("dedupe_key", "like", "organize_identity:%")
|
||||
.where("status", "in", ["open", "investigating", "awaiting_user"])
|
||||
.orderBy("created_at", "desc")
|
||||
.executeTakeFirst();
|
||||
if (!dec) throw new ApiException("conflict", "这条记录不是「没识别出作品」,不能让智能体识别");
|
||||
if (typeof (dec.evidence as { downloadTaskId?: unknown } | null)?.downloadTaskId !== "string")
|
||||
throw new ApiException("conflict", "这条记录没有关联的下载任务。用整理向导手动整理");
|
||||
if (dec.status === "investigating") return { decisionId: dec.id, queued: false };
|
||||
await d.ctx.engine.enqueue(
|
||||
"resolveDecision",
|
||||
{ decisionId: dec.id, trigger: "identify" },
|
||||
{ idempotencyKey: `resolveDecision:identify:${dec.id}:${randomUUID()}`, traceId: dec.id },
|
||||
);
|
||||
return { decisionId: dec.id, queued: true };
|
||||
},
|
||||
{ tag: TAG },
|
||||
);
|
||||
|
||||
// 手动发起整理:与自动整理走同一冻结计划流程;返回 record/task ID,由任务页追踪。
|
||||
// 先过三道闸(organize-guard.ts):路径守卫(400)→ Move 授权(403)→ 纳管来源的做种义务(409 + 待处理)。
|
||||
mount(
|
||||
@@ -273,6 +354,7 @@ function recordFilters<Q extends SelectQueryBuilder<DB, "organization_record", a
|
||||
if (query.downloadTaskId) q = q.where("download_task_id", "=", query.downloadTaskId);
|
||||
if (query.since) q = q.where("created_at", ">=", new Date(query.since));
|
||||
if (query.organizeOnly) q = q.where("action", "in", ["copy", "move", "in_place", "hardlink"]);
|
||||
if (query.attention) q = q.where(attentionSql());
|
||||
if (query.kind === "none") q = q.where("media_entity_id", "is", null);
|
||||
else if (query.kind)
|
||||
q = q.where("media_entity_id", "in", (eb: ExpressionBuilder<DB, "organization_record">) =>
|
||||
|
||||
@@ -14,6 +14,7 @@ import type { SubscriptionRow } from "@umt/db";
|
||||
import type { Context } from "hono";
|
||||
import type { AuthEnv } from "../../../http/auth.ts";
|
||||
import { ApiException } from "../../../http/errors.ts";
|
||||
import { enqueueWatchedRefresh } from "../../sources-identity/service/watched.ts";
|
||||
import type { ModuleApp } from "../../types.ts";
|
||||
import { ensureSubscriptionSlot } from "../services/acquisition.ts";
|
||||
import type { AoDeps, Exec } from "../services/common.ts";
|
||||
@@ -378,6 +379,8 @@ export function registerSubscriptionRoutes(app: ModuleApp, d: AoDeps) {
|
||||
return r;
|
||||
});
|
||||
if (row.media_entity_id) {
|
||||
// 建订阅 = 作品进入关注范围:从没刷新过元数据的补排 full 刷新(集数两层,见 sources-identity/service/watched.ts)
|
||||
await enqueueWatchedRefresh(d.ctx, row.media_entity_id, "subscription");
|
||||
await kickEvaluate(d, { subscriptionId: row.id });
|
||||
// 新订阅:立即主动搜索一次(之后按周期);剧集先刷新元数据拿季总集数
|
||||
await enqueueSubscriptionSearch(d, row.id, "created").catch((err) =>
|
||||
|
||||
@@ -35,6 +35,7 @@ import {
|
||||
import { mergeObservedDownloadState, toDomainDownloadStatus } from "@umt/mapping";
|
||||
import { withAttemptToken } from "@umt/tasks";
|
||||
import { createEntityEpisodeMapper, publishedAtOf } from "../../sources-identity/service/episode-resolution.ts";
|
||||
import { enqueueWatchedRefresh } from "../../sources-identity/service/watched.ts";
|
||||
import { errMessage, jsonb } from "../util.ts";
|
||||
import { parsedOf } from "./acquisition.ts";
|
||||
import {
|
||||
@@ -266,6 +267,9 @@ export async function submitDownload(d: AoDeps, planId: string, opts: { runId?:
|
||||
.selectAll()
|
||||
.where("id", "=", plan.source_release_id)
|
||||
.executeTakeFirstOrThrow();
|
||||
// 开始下载 = 作品进入关注范围:从没刷新过元数据的(自动建档时不在关注范围)补排一次 full 刷新(集数两层,见 watched.ts)
|
||||
const watchedEntity = ev.mediaEntityId ?? rel.media_entity_id;
|
||||
if (watchedEntity) await enqueueWatchedRefresh(d.ctx, watchedEntity, "download");
|
||||
const site = await db.selectFrom("site").selectAll().where("id", "=", rel.site_id).executeTakeFirst();
|
||||
const client = await d.ports.downloader(topo.inst);
|
||||
const tag = topo.inst.managed_tag;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { reasonSentence } from "@umt/contracts";
|
||||
import { type DecisionOption, type RecordAttention, reasonSentence } from "@umt/contracts";
|
||||
import { type OrganizationRecordRow, sql } from "@umt/db";
|
||||
import { errMessage, jsonb } from "../util.ts";
|
||||
import { type AoDeps, type Exec, enqueueSweep, timeSlot, upsertDecision } from "./common.ts";
|
||||
@@ -9,11 +9,111 @@ import { finalizeRecord, removeMovedDownload } from "./organize-finalize.ts";
|
||||
// 入库:冻结整理计划(organization_record + 文件明细)→ 逐文件可恢复执行(操作账本 fencing)→
|
||||
// 资产/位置/路径绑定同事务登记 → Slot 推进 → Move 后移除 qB 任务记录(不删数据)。
|
||||
|
||||
// ── 需要处理(2026-10-06 去掉待处理中心:整理侧的问题在整理记录里就地处理) ──
|
||||
|
||||
const OPEN_DECISION = ["open", "investigating", "awaiting_user"] as const;
|
||||
|
||||
/**
|
||||
* 一条整理记录「需要处理」的口径(列表筛选、统计、首页 / 运行状态汇总共用):
|
||||
* 没被同一下载任务后来的整理记录取代,并且
|
||||
* (有关联的未关闭事项(subject = 这条记录)) 或 (失败 / 部分完成且没被用户忽略)。
|
||||
* alias:外层 organization_record 的别名(kysely selectFrom("organization_record") 即表名)。
|
||||
*/
|
||||
export function attentionSql(alias = "organization_record") {
|
||||
const r = sql.raw(alias);
|
||||
return sql<boolean>`(not exists (
|
||||
select 1 from organization_record r2
|
||||
where ${r}.download_task_id is not null and r2.download_task_id = ${r}.download_task_id
|
||||
and r2.created_at > ${r}.created_at)
|
||||
and (exists (
|
||||
select 1 from decision dd
|
||||
where dd.subject_type = 'organization_record' and dd.subject_id = ${r}.id
|
||||
and dd.status in ('open', 'investigating', 'awaiting_user'))
|
||||
or (${r}.status in ('failed', 'partial') and ${r}.attention_cleared_at is null)))`;
|
||||
}
|
||||
|
||||
/** 事项归到哪类处理:没识别出作品 / 目标冲突 / 其它 */
|
||||
function attentionTopic(dedupeKey: string | null, kind: string | null, reason: string | null) {
|
||||
if (dedupeKey?.startsWith("organize_identity:") || reason?.startsWith("identity_unknown")) return "identity" as const;
|
||||
if (dedupeKey?.startsWith("organize_blocked:") || kind === "path_conflict" || reason?.startsWith("blocked"))
|
||||
return "conflict" as const;
|
||||
return "other" as const;
|
||||
}
|
||||
|
||||
async function loadAttention(exec: Exec, rows: OrganizationRecordRow[]) {
|
||||
const ids = rows.map((r) => r.id);
|
||||
const [decisions, superseded] = await Promise.all([
|
||||
exec
|
||||
.selectFrom("decision")
|
||||
.select([
|
||||
"id",
|
||||
"kind",
|
||||
"status",
|
||||
"title",
|
||||
"summary",
|
||||
"options",
|
||||
"agent_run_id",
|
||||
"evidence",
|
||||
"dedupe_key",
|
||||
"subject_id",
|
||||
])
|
||||
.where("subject_type", "=", "organization_record")
|
||||
.where("subject_id", "in", ids)
|
||||
.where("status", "in", [...OPEN_DECISION])
|
||||
.orderBy("created_at", "desc")
|
||||
.execute(),
|
||||
exec
|
||||
.selectFrom("organization_record as r")
|
||||
.select("r.id")
|
||||
.where("r.id", "in", ids)
|
||||
.where((eb) =>
|
||||
eb.exists(
|
||||
eb
|
||||
.selectFrom("organization_record as r2")
|
||||
.select("r2.id")
|
||||
.whereRef("r2.download_task_id", "=", "r.download_task_id")
|
||||
.whereRef("r2.created_at", ">", "r.created_at"),
|
||||
),
|
||||
)
|
||||
.execute(),
|
||||
]);
|
||||
const old = new Set(superseded.map((x) => x.id));
|
||||
const out = new Map<string, RecordAttention | null>();
|
||||
for (const r of rows) {
|
||||
const d = decisions.find((x) => x.subject_id === r.id) ?? null;
|
||||
const failed = (r.status === "failed" || r.status === "partial") && !r.attention_cleared_at;
|
||||
if (old.has(r.id) || (!d && !failed)) {
|
||||
out.set(r.id, null);
|
||||
continue;
|
||||
}
|
||||
const topic = attentionTopic(d?.dedupe_key ?? null, d?.kind ?? null, r.reason);
|
||||
const ev = (d?.evidence ?? {}) as Record<string, unknown>;
|
||||
out.set(r.id, {
|
||||
topic,
|
||||
decision: d
|
||||
? {
|
||||
id: d.id,
|
||||
kind: d.kind,
|
||||
status: d.status,
|
||||
title: d.title,
|
||||
summary: d.summary,
|
||||
options: (d.options ?? []) as DecisionOption[],
|
||||
agentRunId: d.agent_run_id,
|
||||
evidence: ev,
|
||||
}
|
||||
: null,
|
||||
agentIdentify: !!d && d.dedupe_key.startsWith("organize_identity:") && typeof ev.downloadTaskId === "string",
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ── 公开记录映射 ──
|
||||
|
||||
export async function loadRecordsPublic(exec: Exec, rows: OrganizationRecordRow[], includeFiles: boolean) {
|
||||
if (rows.length === 0) return [];
|
||||
const ids = rows.map((r) => r.id);
|
||||
const attention = await loadAttention(exec, rows);
|
||||
const entityIds = [...new Set(rows.map((r) => r.media_entity_id).filter((x): x is string => !!x))];
|
||||
const dlIds = [...new Set(rows.map((r) => r.download_task_id).filter((x): x is string => !!x))];
|
||||
const [files, ops, entities, idents, units, sizes, dls] = await Promise.all([
|
||||
@@ -196,6 +296,7 @@ export async function loadRecordsPublic(exec: Exec, rows: OrganizationRecordRow[
|
||||
startedAt: iso(r.started_at),
|
||||
finishedAt: iso(r.finished_at),
|
||||
changeSeq: String(r.change_seq),
|
||||
attention: attention.get(r.id) ?? null,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
@@ -326,13 +326,7 @@ export function organizeDecisionHook(d: AoDeps): DecisionHook {
|
||||
if (row.dedupe_key.startsWith("organize_identity:")) {
|
||||
if (!dt) throw new HookError("not_found", "关联的下载任务不存在");
|
||||
const entityId = await chosenEntity(d, body, opt, actor);
|
||||
await d.ctx.db
|
||||
.updateTable("download_task")
|
||||
.set({ media_entity_id: entityId })
|
||||
.where("id", "=", dt.id)
|
||||
.execute();
|
||||
const r = await startManualImport(d, { downloadTaskId: dt.id, mediaEntityId: entityId }, actor, "decision");
|
||||
return { kind: "organize", mediaEntityId: entityId, ...r };
|
||||
return reorganizeAs(d, dt.id, entityId, actor, "decision");
|
||||
}
|
||||
// organize_blocked:目标已存在 → 替换 / 保留两者 / 跳过
|
||||
const key = body.optionKey;
|
||||
@@ -367,6 +361,84 @@ export function organizeDecisionHook(d: AoDeps): DecisionHook {
|
||||
};
|
||||
}
|
||||
|
||||
/** 回填下载任务的作品后按该作品重新整理(人工指定与智能体识别共用) */
|
||||
async function reorganizeAs(
|
||||
d: AoDeps,
|
||||
downloadTaskId: string,
|
||||
entityId: string,
|
||||
actor: DecisionHookActor,
|
||||
via: string,
|
||||
) {
|
||||
await d.ctx.db
|
||||
.updateTable("download_task")
|
||||
.set({ media_entity_id: entityId })
|
||||
.where("id", "=", downloadTaskId)
|
||||
.execute();
|
||||
const r = await startManualImport(d, { downloadTaskId, mediaEntityId: entityId }, actor, via);
|
||||
return { kind: "organize", mediaEntityId: entityId, ...r };
|
||||
}
|
||||
|
||||
const OPEN_DECISION = ["open", "investigating", "awaiting_user"];
|
||||
|
||||
/**
|
||||
* organize.assign_identity:智能体给「没识别出作品」的整理事项指定作品(本地作品或 TMDB),随即重新整理并关闭事项。
|
||||
* 与人工在整理记录里「指定作品」走同一条路(回填下载任务 → 冻结手动整理计划 → 入队执行)。
|
||||
*/
|
||||
export async function assignOrganizeIdentity(
|
||||
d: AoDeps,
|
||||
decisionId: string,
|
||||
pick: { mediaEntityId?: string | undefined; tmdb?: { type: "movie" | "tv"; id: string } | undefined },
|
||||
actor: DecisionHookActor,
|
||||
note: string,
|
||||
): Promise<{ mediaEntityId: string; recordId: string | null; status: string; decisionStatus: "resolved" }> {
|
||||
const db = d.ctx.db;
|
||||
const row = await db.selectFrom("decision").selectAll().where("id", "=", decisionId).executeTakeFirst();
|
||||
if (!row) throw new HookError("not_found", "事项不存在");
|
||||
if (!row.dedupe_key.startsWith("organize_identity:"))
|
||||
throw new HookError("bad_request", "只能用于整理时「没识别出作品」的事项");
|
||||
if (!OPEN_DECISION.includes(row.status)) throw new HookError("conflict", "这条记录已经处理过了");
|
||||
const ev = (row.evidence ?? {}) as { downloadTaskId?: string | null };
|
||||
const dtId = ev.downloadTaskId ?? null;
|
||||
if (!dtId) throw new HookError("not_found", "这条记录没有关联的下载任务,只能在整理向导里手动整理");
|
||||
const entityId = pick.mediaEntityId
|
||||
? await chosenEntity(
|
||||
d,
|
||||
{ identity: { mediaEntityId: pick.mediaEntityId } },
|
||||
{ key: "x", label: "x", input: { requires: "mediaEntityId" } },
|
||||
actor,
|
||||
)
|
||||
: await chosenEntity(
|
||||
d,
|
||||
{ identity: { tmdb: pick.tmdb } },
|
||||
{ key: "x", label: "x", input: { requires: "tmdb" } },
|
||||
actor,
|
||||
);
|
||||
const r = await reorganizeAs(d, dtId, entityId, actor, "agent-identify");
|
||||
const by = actor.id ? `${actor.type}:${actor.id}` : actor.type;
|
||||
await db.transaction().execute(async (trx) => {
|
||||
const closed = await trx
|
||||
.updateTable("decision")
|
||||
.set({
|
||||
status: "resolved",
|
||||
resolution: jsonb({ optionKey: null, note, by, execution: { ...r, via: "organize.assign_identity" } }),
|
||||
resolved_by: by,
|
||||
resolved_at: new Date(),
|
||||
})
|
||||
.where("id", "=", decisionId)
|
||||
.where("status", "in", OPEN_DECISION as never[])
|
||||
.returning("id")
|
||||
.executeTakeFirst();
|
||||
if (closed)
|
||||
await d.ctx.outbox.emit(
|
||||
trx,
|
||||
"decision.updated",
|
||||
{ decisionId, status: "resolved" },
|
||||
{ idempotencyKey: `decision.updated:${decisionId}:resolved` },
|
||||
);
|
||||
});
|
||||
return { mediaEntityId: entityId, recordId: r.recordId, status: r.status, decisionStatus: "resolved" };
|
||||
}
|
||||
|
||||
/** 已登记下载任务里,内容路径(本机视图)与这些源路径重叠的(手动按路径整理时找回对应下载任务) */
|
||||
export async function downloadTasksUnder(exec: Exec, paths: readonly string[]): Promise<DownloadTaskRow[]> {
|
||||
if (paths.length === 0) return [];
|
||||
|
||||
@@ -4,6 +4,7 @@ import type { CapabilitySpec } from "@umt/contracts";
|
||||
import { type DB, type Kysely, sql } from "@umt/db";
|
||||
import type { SettingsReader } from "../types.ts";
|
||||
import { inlineApproval, optionApproval, proposeFirstBlock } from "./interaction.ts";
|
||||
import { investigationDecisionId } from "./runner.ts";
|
||||
import { exceedsAncestors } from "./subagents.ts";
|
||||
|
||||
// 服务端授权(REQ §10.2、§10.3):propose/approve/execute 类能力必须命中
|
||||
@@ -233,6 +234,24 @@ export function createAuthorizer(deps: {
|
||||
if (block) return { allowed: false, reason: block };
|
||||
}
|
||||
|
||||
// 整理没识别出作品(organize.assign_identity):只放行这条事项的智能体识别会话(dedupe investigate:<事项>)与用户发起的对话;
|
||||
// 不需要持续授权(用户在设置里开着「整理识别失败时叫智能体识别」即同意,默认开启)
|
||||
if (d.id === "organize.assign_identity") {
|
||||
if (!runId || (ctx.source !== "agent" && ctx.source !== "task"))
|
||||
return { allowed: false, reason: "只有智能体会话或控制台可以指定整理作品" };
|
||||
const r = await db
|
||||
.selectFrom("agent_run")
|
||||
.select(["trigger", "dedupe_key"])
|
||||
.where("id", "=", runId)
|
||||
.executeTakeFirst();
|
||||
if (r?.trigger === "user") return { allowed: true };
|
||||
const target = typeof inp.decisionId === "string" ? inp.decisionId : null;
|
||||
const own = investigationDecisionId(r?.dedupe_key);
|
||||
return target && own === target
|
||||
? { allowed: true }
|
||||
: { allowed: false, reason: "只能处理本次识别的那条整理记录" };
|
||||
}
|
||||
|
||||
// 视觉子流程(spawn_reason = browser.solve_challenge)里的坐标动作:父会话那次 solve_challenge 已过授权,
|
||||
// 步数 / 预算 / 白名单由子流程约束,这里随之放行(否则只授权 solve_challenge 时子流程一步也点不了)
|
||||
if (runId && CHALLENGE_STEP_CAPS.has(d.id)) {
|
||||
|
||||
@@ -78,9 +78,8 @@ export function systemChallengeVision(env: () => AgentEnv, registry: CapabilityR
|
||||
success: { textAbsent: req.textAbsent ?? "Just a moment" },
|
||||
maxSteps: Math.min(12, Math.max(1, req.maxSteps)),
|
||||
budget: {
|
||||
// 不设 token / 费用上限(2026-10-06);步数与时长是防跑飞限制
|
||||
maxDurationSec: Math.min(120, s.agent.maxDurationSec),
|
||||
...(s.agent.maxTokensPerRun ? { maxTokens: Math.max(1000, s.agent.maxTokensPerRun) } : {}),
|
||||
...(s.agent.maxCostUsdPerRun ? { maxCostUsd: s.agent.maxCostUsdPerRun } : {}),
|
||||
},
|
||||
};
|
||||
const hctx = {
|
||||
|
||||
@@ -2,8 +2,16 @@ import type { DecisionOption, DownloadStatus } from "@umt/contracts";
|
||||
import { type DecisionRow, sql } from "@umt/db";
|
||||
import type { ServerContext } from "../types.ts";
|
||||
import { GRANT_ACTIONS } from "./authorize.ts";
|
||||
import { type DriveResult, INVESTIGATE_CAPABILITIES, RECOVER_CAPABILITIES, RECOVERY_ACTIONS } from "./runner.ts";
|
||||
import {
|
||||
type DriveResult,
|
||||
INVESTIGATE_CAPABILITIES,
|
||||
investigationDecisionId,
|
||||
ORGANIZE_IDENTIFY_CAPABILITIES,
|
||||
RECOVER_CAPABILITIES,
|
||||
RECOVERY_ACTIONS,
|
||||
} from "./runner.ts";
|
||||
import { startRun } from "./service.ts";
|
||||
import { ORGANIZE_IDENTIFY_ACTOR } from "./usage.ts";
|
||||
|
||||
// 后台自动调查与授权内恢复(REQ §8.4.2、§10.7、AT68 / AT71):
|
||||
// decision.created → autoInvestigate:按 settings.agent.autoInvestigateMode 决定只读调查或授权内恢复,
|
||||
@@ -13,6 +21,9 @@ import { startRun } from "./service.ts";
|
||||
// 按业务事实(download_task / task / source_release 状态;集数映射看事项内资源是否都已不是待确认)核实恢复结果,
|
||||
// 核实成功才关闭事项;
|
||||
// 失败 / 超时 / 预算超限一律保持待处理(finalize 把事项转为 awaiting_user),不自动再试。
|
||||
// 整理没识别出作品(organize_identity:*):不看 autoInvestigate,按 agent.autoIdentifyOrganize(缺省开)派一次智能体识别,
|
||||
// 认出来调 organize.assign_identity 指定作品并重新整理(事项随即关闭);认不出停在整理记录「需要处理」里,
|
||||
// 用户可在那里再点「让智能体识别」(manual,另起一个会话)。
|
||||
|
||||
const KINDS = ["identity_ambiguous", "download_failed", "download_stalled", "episode_mapping"] as const;
|
||||
export const AUTO_ACTOR = "system:auto-investigate";
|
||||
@@ -66,8 +77,7 @@ export interface RecoveryOutcome {
|
||||
summary: string;
|
||||
}
|
||||
|
||||
const decisionIdOf = (dedupeKey: string | null | undefined) =>
|
||||
dedupeKey?.startsWith("investigate:") ? dedupeKey.slice("investigate:".length) : null;
|
||||
const decisionIdOf = investigationDecisionId;
|
||||
|
||||
export const isInvestigationRun = (run: { dedupe_key: string | null }) => decisionIdOf(run.dedupe_key) !== null;
|
||||
|
||||
@@ -128,12 +138,13 @@ async function relatedTask(ctx: ServerContext, d: DecisionRow) {
|
||||
}
|
||||
|
||||
function suggestionFor(d: DecisionRow, reason: string): string {
|
||||
if (d.dedupe_key.startsWith("organize_identity:")) return `${reason}。可在整理记录里指定作品或重新整理。`;
|
||||
if (d.kind === "identity_ambiguous")
|
||||
return `${reason}。可在待处理中手动选择身份,或为 identity.resolve 发放持续授权。`;
|
||||
return `${reason}。可在媒体库「未识别」里手动指定作品,或为 identity.resolve 发放持续授权。`;
|
||||
if (d.kind === "episode_mapping")
|
||||
return `${reason}。智能体模拟通过的规则会作为建议留在事项上,可在待处理中确认;或为 episode_mapping.apply_rule 发放持续授权。`;
|
||||
return `${reason}。智能体模拟通过的规则会作为建议留在作品的集数映射里,可在那里确认;或为 episode_mapping.apply_rule 发放持续授权。`;
|
||||
return (
|
||||
`${reason}。可在待处理中选择"强制重新校验"(download.recheck),或为 download.recheck / task.retry 发放持续授权;` +
|
||||
`${reason}。可在下载详情里「强制重新校验」(download.recheck),或为 download.recheck / task.retry 发放持续授权;` +
|
||||
`换源、删除需人工决定。`
|
||||
);
|
||||
}
|
||||
@@ -167,8 +178,10 @@ async function addRecheckOption(ctx: ServerContext, d: DecisionRow) {
|
||||
export async function autoInvestigate(
|
||||
ctx: ServerContext,
|
||||
decisionId: string,
|
||||
opts: { manual?: boolean } = {},
|
||||
): Promise<{ runId: string | null; created: boolean; mode?: "investigate" | "recover"; skipped?: string }> {
|
||||
const d = await ctx.db.selectFrom("decision").selectAll().where("id", "=", decisionId).executeTakeFirst();
|
||||
if (d?.dedupe_key.startsWith("organize_identity:")) return identifyOrganize(ctx, d, opts.manual === true);
|
||||
if (d?.status !== "open") return { runId: null, created: false };
|
||||
if (!(KINDS as readonly string[]).includes(d.kind)) return { runId: null, created: false };
|
||||
// Agent 自己引起的事项不再触发 Agent(防止递归自触发)
|
||||
@@ -284,6 +297,96 @@ export async function autoInvestigate(
|
||||
return { runId: run.id, created, mode };
|
||||
}
|
||||
|
||||
/** 证据里的字段转成给模型看的一句(没有就空) */
|
||||
function evidenceLine(ev: Record<string, unknown>): string {
|
||||
const parsed = (ev.parsed ?? {}) as Record<string, unknown>;
|
||||
const parts = [
|
||||
typeof ev.torrentName === "string" ? `种子名「${ev.torrentName}」` : "",
|
||||
typeof ev.mainFile === "string" ? `主视频「${ev.mainFile}」` : "",
|
||||
parsed.title ? `解析出的标题「${String(parsed.title)}」` : "",
|
||||
parsed.year ? `年份 ${String(parsed.year)}` : "",
|
||||
parsed.season != null ? `第 ${String(parsed.season)} 季` : "",
|
||||
Array.isArray(parsed.episodes) && parsed.episodes.length ? `集 ${parsed.episodes.join("、")}` : "",
|
||||
].filter(Boolean);
|
||||
const cands = Array.isArray(ev.candidates) ? (ev.candidates as Record<string, unknown>[]).slice(0, 5) : [];
|
||||
const candText = cands.length
|
||||
? `;常规识别的候选:${cands
|
||||
.map(
|
||||
(c) =>
|
||||
`${String(c.title ?? "?")}${c.year ? ` (${String(c.year)})` : ""}${c.externalId ? ` tmdb:${String(c.entityType ?? "")}/${String(c.externalId)}` : ""}${c.localEntityId ? ` 本地作品 ${String(c.localEntityId)}` : ""}`,
|
||||
)
|
||||
.join(";")}`
|
||||
: "";
|
||||
return parts.length ? `${parts.join(",")}${candText}。` : candText ? `${candText.slice(1)}。` : "";
|
||||
}
|
||||
|
||||
/**
|
||||
* 整理没识别出作品 → 智能体识别一次(设置 agent.autoIdentifyOrganize,缺省开;manual = 用户在整理记录里点「让智能体识别」,
|
||||
* 不看开关、事项已转人工也可以,另起一个会话)。会话在白名单内查作品,有把握才调 organize.assign_identity;
|
||||
* 结果按恢复动作核实(事项关闭 = 已指定并重新整理),没认出来事项转 awaiting_user,留在整理记录「需要处理」里。
|
||||
*/
|
||||
export async function identifyOrganize(
|
||||
ctx: ServerContext,
|
||||
d: DecisionRow,
|
||||
manual: boolean,
|
||||
): Promise<{ runId: string | null; created: boolean; mode?: "recover"; skipped?: string }> {
|
||||
if (manual) {
|
||||
if (!["open", "awaiting_user"].includes(d.status))
|
||||
return d.status === "investigating" && d.agent_run_id
|
||||
? { runId: d.agent_run_id, created: false, skipped: "running" }
|
||||
: { runId: null, created: false, skipped: `status_${d.status}` };
|
||||
} else {
|
||||
if (d.status !== "open") return { runId: null, created: false };
|
||||
const s = await ctx.settings.get("agent");
|
||||
if (!s.autoIdentifyOrganize) return { runId: null, created: false, skipped: "disabled" };
|
||||
}
|
||||
const s = await ctx.settings.get("agent");
|
||||
const ev = (d.evidence ?? {}) as Record<string, unknown>;
|
||||
const goal = [
|
||||
`识别整理记录里的作品(待处理事项 ${d.id}):${d.title}。`,
|
||||
evidenceLine(ev),
|
||||
"用 catalog.lookup 按标题 / 年份查 TMDB,用 inventory.query 看媒体库里有没有这个作品;标题是拼音、缩写或译名对不上时可以用 web.search 查正式名称。",
|
||||
`确认标题、年份、类型(电影 / 剧集)和季集都对得上时,调用一次 organize.assign_identity(decisionId 填 ${d.id},` +
|
||||
"本地已有作品填 mediaEntityId,否则填 tmdb 类型和 ID,reasons 写依据),系统会按这个作品重新整理。",
|
||||
"拿不准就不要指定,只说明查到了什么、为什么认不出。不下载、不删除、不改别的记录。",
|
||||
].join("");
|
||||
const { run, created } = await startRun(ctx, {
|
||||
goal,
|
||||
mode: "execute",
|
||||
capabilityAllowlist: [...ORGANIZE_IDENTIFY_CAPABILITIES],
|
||||
trigger: "event",
|
||||
createdBy: ORGANIZE_IDENTIFY_ACTOR,
|
||||
dedupeKey: manual ? `investigate:${d.id}#${Date.now()}` : `investigate:${d.id}`,
|
||||
budget: { maxToolCalls: s.investigateMaxToolCalls, maxDurationSec: Math.min(900, s.maxDurationSec) },
|
||||
});
|
||||
if (created) {
|
||||
const r = await ctx.db
|
||||
.updateTable("decision")
|
||||
.set({ status: "investigating", agent_run_id: run.id })
|
||||
.where("id", "=", d.id)
|
||||
.where("status", "in", ["open", "awaiting_user"])
|
||||
.returning("id")
|
||||
.executeTakeFirst();
|
||||
if (r) {
|
||||
await mergeEvidence(ctx, d.id, {
|
||||
mode: "recover",
|
||||
requestedMode: "recover",
|
||||
attempt: 1,
|
||||
maxAttempts: 1,
|
||||
recoverAttempted: true,
|
||||
runId: run.id,
|
||||
});
|
||||
await ctx.outbox.emit(
|
||||
ctx.db,
|
||||
"decision.updated",
|
||||
{ decisionId: d.id, status: "investigating" },
|
||||
{ idempotencyKey: `decision.updated:${d.id}:investigating:${run.id}` },
|
||||
);
|
||||
}
|
||||
}
|
||||
return { runId: run.id, created, mode: "recover" };
|
||||
}
|
||||
|
||||
/** 本 run 调用过的恢复动作(账本)与被拒绝的调用(审计) */
|
||||
export async function recoveryActions(
|
||||
ctx: ServerContext,
|
||||
@@ -356,6 +459,14 @@ export async function checkRecovery(ctx: ServerContext, actions: RecoveryAction[
|
||||
: undefined;
|
||||
facts[`source_release:${id}`] = r ? { resolutionStatus: r.resolution_status } : null;
|
||||
states.push(r?.resolution_status === "resolved" && r.media_entity_id ? "recovered" : "pending");
|
||||
} else if (a.capabilityId === "organize.assign_identity") {
|
||||
// 指定作品后事项随即关闭、重新整理已入队;事项关闭即视为恢复(整理结果看整理记录)
|
||||
const id = String(a.input.decisionId ?? "");
|
||||
const d = id
|
||||
? await ctx.db.selectFrom("decision").select(["status"]).where("id", "=", id).executeTakeFirst()
|
||||
: undefined;
|
||||
facts[`decision:${id}`] = d ? { status: d.status } : null;
|
||||
states.push(!d ? "failed" : d.status === "resolved" ? "recovered" : "pending");
|
||||
} else if (a.capabilityId === "episode_mapping.apply_rule") {
|
||||
// 事项内资源都已不是待确认(规则写入后的重算会把事项自动关闭)即视为恢复
|
||||
const id = String(a.input.decisionId ?? "");
|
||||
@@ -415,15 +526,15 @@ export async function applyRecoveryOutcome(
|
||||
? `已恢复(系统核实):执行 ${what} 后业务状态已恢复。`
|
||||
: outcome === "failed"
|
||||
? done.length > 0
|
||||
? `未恢复:执行 ${what} 后业务状态仍为失败,已退回待处理。`
|
||||
: `未恢复:${what} 执行失败,已退回待处理。`
|
||||
? `未恢复:执行 ${what} 后业务状态仍为失败,已交还人工。`
|
||||
: `未恢复:${what} 执行失败,已交还人工。`
|
||||
: outcome === "unverified"
|
||||
? `未恢复:执行 ${what} 后在核实时限内业务状态未恢复,已退回待处理。`
|
||||
? `未恢复:执行 ${what} 后在核实时限内业务状态未恢复,已交还人工。`
|
||||
: outcome === "budget_exceeded"
|
||||
? `未恢复:调查超出预算(${res.message ?? ""}),未执行恢复动作,已退回待处理。`
|
||||
? `未恢复:调查超出预算(${res.message ?? ""}),未执行恢复动作,已交还人工。`
|
||||
: outcome === "cancelled"
|
||||
? "未恢复:运行已取消。"
|
||||
: `未恢复:没有执行恢复动作${acts.denied.length ? `(被拒绝:${acts.denied.map((x) => x.capabilityId).join(", ")})` : ""},已退回待处理。`;
|
||||
: `未恢复:没有执行恢复动作${acts.denied.length ? `(被拒绝:${acts.denied.map((x) => x.capabilityId).join(", ")})` : ""},已交还人工。`;
|
||||
const evidence: Partial<AutoRecoverEvidence> = {
|
||||
runId,
|
||||
outcome,
|
||||
|
||||
@@ -19,6 +19,7 @@ import { afterApprovalDecided, answerOptions } from "./interaction.ts";
|
||||
import { type InvokeLimiter, sharedInvokeLimiter, UpstreamBusyError, UpstreamTimeoutError } from "./invoke-limits.ts";
|
||||
import { AgentRunError, abortRun, appendMessage, startRun } from "./service.ts";
|
||||
import { descendants, descendantUsage } from "./subagents.ts";
|
||||
import { agentUsage } from "./usage.ts";
|
||||
|
||||
// Agent 会话 API、持续授权 / 单次审批、能力目录与调用、业务任务。
|
||||
|
||||
@@ -119,6 +120,8 @@ export function registerAgentRoutes(
|
||||
const dispatch = new InternalDispatcher(app);
|
||||
|
||||
// ── Agent 会话 ──
|
||||
route(app, Api.agentRuns.usage, async () => agentUsage(db()));
|
||||
|
||||
route(app, Api.agentRuns.list, async ({ query }) => {
|
||||
let q = db().selectFrom("agent_run").selectAll();
|
||||
if (query.status) q = q.where("status", "=", query.status);
|
||||
|
||||
@@ -91,12 +91,35 @@ export const RECOVER_CAPABILITIES = [
|
||||
"download.recheck",
|
||||
"episode_mapping.apply_rule",
|
||||
] as const;
|
||||
/**
|
||||
* 整理没识别出作品时的智能体识别:查作品(TMDB / 媒体库 / 网页)+ 指定作品并重新整理。
|
||||
* 不能下载、删除、改别的事项;organize.assign_identity 只放行本事项(authorize.ts)
|
||||
*/
|
||||
export const ORGANIZE_IDENTIFY_CAPABILITIES = [
|
||||
"catalog.lookup",
|
||||
"inventory.query",
|
||||
"release.inspect",
|
||||
"download.inspect",
|
||||
"task.inspect",
|
||||
"decision.list",
|
||||
"web.search",
|
||||
"web.fetch",
|
||||
"organize.assign_identity",
|
||||
] as const;
|
||||
/**
|
||||
* 后台调查会话的去重键 investigate:<事项 id>;用户在整理记录里再点一次「让智能体识别」时加 #<序号> 另起一个会话。
|
||||
* 返回事项 id,不是调查会话返回 null
|
||||
*/
|
||||
export function investigationDecisionId(dedupeKey: string | null | undefined): string | null {
|
||||
return dedupeKey?.startsWith("investigate:") ? (dedupeKey.slice("investigate:".length).split("#")[0] ?? null) : null;
|
||||
}
|
||||
/** 被视为"恢复动作"的能力(结果需系统核实) */
|
||||
export const RECOVERY_ACTIONS = [
|
||||
"task.retry",
|
||||
"download.recheck",
|
||||
"identity.resolve",
|
||||
"episode_mapping.apply_rule",
|
||||
"organize.assign_identity",
|
||||
] as const;
|
||||
|
||||
export interface RunScope {
|
||||
@@ -162,8 +185,9 @@ export function agentSettings(
|
||||
upstream: RunUpstream,
|
||||
): AgentSettings {
|
||||
const pi = s.pi;
|
||||
const maxTokens = budget.maxTokens ?? s.agent.maxTokensPerRun ?? undefined;
|
||||
const maxCost = budget.maxCostUsd ?? s.agent.maxCostUsdPerRun ?? undefined;
|
||||
// 设置里不再有 token / 费用上限(2026-10-06);只有调用方显式划拨(子会话、巡检预算)时才限制
|
||||
const maxTokens = budget.maxTokens;
|
||||
const maxCost = budget.maxCostUsd;
|
||||
const up = upstream.row;
|
||||
return {
|
||||
provider: up.provider,
|
||||
@@ -387,20 +411,6 @@ async function lastOutcomeEvent(env: AgentEnv, runId: string) {
|
||||
return r ?? null;
|
||||
}
|
||||
|
||||
async function dailyBudgetBlock(env: AgentEnv, s: GlobalSettings, run: AgentRunRow): Promise<string | null> {
|
||||
if (run.started_at) return null; // 续跑不重复计数
|
||||
const day = new Date();
|
||||
day.setHours(0, 0, 0, 0);
|
||||
const r = await sql<{ n: number; cost: number | null }>`
|
||||
select count(*)::int as n, sum(coalesce((usage->>'costUsd')::float8, 0))::float8 as cost
|
||||
from agent_run where started_at >= ${day} and id <> ${run.id}`.execute(env.ctx.db);
|
||||
const n = r.rows[0]?.n ?? 0;
|
||||
const cost = r.rows[0]?.cost ?? 0;
|
||||
if (n >= s.budget.agentMaxRunsPerDay) return `今日智能体运行次数已达上限 ${s.budget.agentMaxRunsPerDay}`;
|
||||
if (cost >= s.budget.agentMaxCostUsdPerDay) return `今日智能体费用已达上限 $${s.budget.agentMaxCostUsdPerDay}`;
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 驱动一次模型会话直到本轮结束(含追加消息)。整个函数在一个持久步骤里执行:worker 崩溃后新 worker 从头重跑本函数,
|
||||
* 打开同一 JSONL 会话,pendingOperations>0 时对账 + resume,已完成的工具调用不会重放。
|
||||
@@ -416,9 +426,8 @@ export async function drive(
|
||||
const run = await ctx.db.selectFrom("agent_run").selectAll().where("id", "=", runId).executeTakeFirstOrThrow();
|
||||
if (run.cancel_requested_at || signal.aborted)
|
||||
return { status: "cancelled", reason: "aborted", budget: null, message: "运行已被取消", finalText: "" };
|
||||
// 不设每日次数 / 费用上限(2026-10-06):花费在设置页与运行状态里可见,单次运行只受工具调用次数与时长约束
|
||||
const s = await ctx.settings.all();
|
||||
const blocked = await dailyBudgetBlock(env, s, run);
|
||||
if (blocked) return { status: "failed", reason: "budget", budget: "daily", message: blocked, finalText: "" };
|
||||
|
||||
const scope = (run.scope ?? {}) as unknown as RunScope;
|
||||
// 上游:run.upstream_id(runAgent 的 upstreamId 覆盖)> settings.pi.defaultUpstreamId;都没有直接失败
|
||||
|
||||
@@ -12,7 +12,14 @@ import { type AgentRunRow, type DB, type Kysely, sql } from "@umt/db";
|
||||
import type { ServerContext } from "../types.ts";
|
||||
import { dismissPendingInteractions } from "./interaction.ts";
|
||||
import { buildGoalReport } from "./report.ts";
|
||||
import { type AgentEnv, type DriveResult, INVESTIGATE_CAPABILITIES, publishStatus, scopeFor } from "./runner.ts";
|
||||
import {
|
||||
type AgentEnv,
|
||||
type DriveResult,
|
||||
INVESTIGATE_CAPABILITIES,
|
||||
investigationDecisionId,
|
||||
publishStatus,
|
||||
scopeFor,
|
||||
} from "./runner.ts";
|
||||
import {
|
||||
cascadeCancel,
|
||||
descendants,
|
||||
@@ -364,8 +371,9 @@ export async function finalize(
|
||||
.where("id", "=", runId)
|
||||
.execute();
|
||||
// 后台调查:结论回写待处理事项,交还人工(仍可被新证据重新唤醒)
|
||||
if (run.dedupe_key?.startsWith("investigate:")) {
|
||||
const decisionId = run.dedupe_key.slice("investigate:".length);
|
||||
const investigated = investigationDecisionId(run.dedupe_key);
|
||||
if (investigated) {
|
||||
const decisionId = investigated;
|
||||
await ctx.db.transaction().execute(async (trx) => {
|
||||
const r = await trx
|
||||
.updateTable("decision")
|
||||
|
||||
@@ -471,9 +471,9 @@ function limitsOf(run: AgentRunRow, s: GlobalSettings): Limits {
|
||||
const b = (run.budget ?? {}) as AgentBudget;
|
||||
return {
|
||||
maxToolCalls: b.maxToolCalls ?? s.agent.maxToolCalls,
|
||||
maxTokens: b.maxTokens ?? s.agent.maxTokensPerRun ?? null,
|
||||
maxCostUsd:
|
||||
b.maxCostUsd ?? (s.agent.maxCostUsdPerRun && s.agent.maxCostUsdPerRun > 0 ? s.agent.maxCostUsdPerRun : null),
|
||||
// token / 费用只认本会话显式划拨的额度;设置里不再有全局上限(2026-10-06)
|
||||
maxTokens: b.maxTokens ?? null,
|
||||
maxCostUsd: b.maxCostUsd && b.maxCostUsd > 0 ? b.maxCostUsd : null,
|
||||
maxDurationSec: b.maxDurationSec ?? s.agent.maxDurationSec,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -177,12 +177,15 @@ export function registerAgentTasks(registry: TaskRegistry, env: () => AgentEnv)
|
||||
name: "resolveDecision",
|
||||
version: 1,
|
||||
lane: "agent",
|
||||
inputSchema: z.object({ decisionId: id, trigger: z.enum(["created", "updated"]).default("updated") }),
|
||||
// identify:用户在整理记录里点「让智能体识别」(整理没识别出作品的事项,另起一个识别会话)
|
||||
inputSchema: z.object({ decisionId: id, trigger: z.enum(["created", "updated", "identify"]).default("updated") }),
|
||||
retryPolicy: DB_RETRY,
|
||||
handler: async (t) => {
|
||||
const e = env();
|
||||
if (t.input.trigger === "created")
|
||||
return t.step.run("investigate", () => autoInvestigate(e.ctx, t.input.decisionId));
|
||||
if (t.input.trigger === "identify")
|
||||
return t.step.run("identify", () => autoInvestigate(e.ctx, t.input.decisionId, { manual: true }));
|
||||
return t.step.run("execute", () => executeResolution(e.ctx, t.input.decisionId));
|
||||
},
|
||||
}),
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import type { AgentSpend, AgentSpendBucket, AgentSpendKind } from "@umt/contracts";
|
||||
import { type DB, type Kysely, sql } from "@umt/db";
|
||||
|
||||
// 智能体用量(2026-10-06):不设每日次数 / 费用上限,改为把花费摆出来。按 agent_run 的开始时间(没开始的按创建时间)
|
||||
// 统计今天与最近 7 天,按会话类型分组;费用取 usage.costUsd(上游不报费用时为 0)。
|
||||
|
||||
/** 整理没识别出作品时智能体识别的会话发起者(见 investigate.ts) */
|
||||
export const ORGANIZE_IDENTIFY_ACTOR = "system:organize-identify";
|
||||
|
||||
const KIND_SQL = sql<AgentSpendKind>`case
|
||||
when parent_run_id is not null then 'subagent'
|
||||
when created_by = ${ORGANIZE_IDENTIFY_ACTOR} then 'organize_identify'
|
||||
when trigger = 'schedule' then 'patrol'
|
||||
when trigger = 'event' then 'investigate'
|
||||
else 'chat' end`;
|
||||
|
||||
const ORDER: AgentSpendKind[] = ["chat", "patrol", "investigate", "organize_identify", "subagent"];
|
||||
|
||||
async function bucket(db: Kysely<DB>, since: Date): Promise<AgentSpendBucket> {
|
||||
const r = await sql<{ kind: AgentSpendKind; runs: number; tokens: string | null; cost: number | null }>`
|
||||
select ${KIND_SQL} as kind, count(*)::int as runs,
|
||||
sum(coalesce((usage->>'totalTokens')::bigint, 0))::bigint as tokens,
|
||||
sum(coalesce((usage->>'costUsd')::float8, 0))::float8 as cost
|
||||
from agent_run
|
||||
where coalesce(started_at, created_at) >= ${since}
|
||||
group by 1`.execute(db);
|
||||
const byKind = r.rows
|
||||
.map((x) => ({ kind: x.kind, runs: x.runs, tokens: Number(x.tokens ?? 0), costUsd: x.cost ?? 0 }))
|
||||
.sort((a, b) => ORDER.indexOf(a.kind) - ORDER.indexOf(b.kind));
|
||||
return {
|
||||
runs: byKind.reduce((a, x) => a + x.runs, 0),
|
||||
tokens: byKind.reduce((a, x) => a + x.tokens, 0),
|
||||
costUsd: byKind.reduce((a, x) => a + x.costUsd, 0),
|
||||
byKind,
|
||||
};
|
||||
}
|
||||
|
||||
export async function agentUsage(db: Kysely<DB>, now = new Date()): Promise<AgentSpend> {
|
||||
const today = new Date(now);
|
||||
today.setHours(0, 0, 0, 0);
|
||||
const week = new Date(today.getTime() - 6 * 86_400_000);
|
||||
const [t, w] = await Promise.all([bucket(db, today), bucket(db, week)]);
|
||||
return { today: t, last7d: w };
|
||||
}
|
||||
@@ -23,13 +23,18 @@ const action = (id: string, group: string, title: string, href: string, keywords
|
||||
export const SEARCH_ACTIONS: readonly SearchAction[] = [
|
||||
page("home", "概览", "首页", "/console", ["home", "dashboard", "概览"]),
|
||||
page("agent", "概览", "智能体会话", "/console/agent", ["agent", "会话"]),
|
||||
page("inbox", "概览", "待处理", "/console/inbox", ["inbox", "收件箱", "decision"]),
|
||||
page("schedules", "概览", "计划", "/console/schedules", ["schedule", "cron", "巡检", "计划", "定时任务"]),
|
||||
page("sites", "获取", "站点", "/console/sites", ["site", "pt", "站点账号", "rss", "feed", "bt"]),
|
||||
page("subscriptions", "获取", "订阅", "/console/subscriptions", ["subscription", "追剧"]),
|
||||
page("rules", "获取", "规则", "/console/rules", ["rules", "收录策略", "policy"]),
|
||||
page("downloads", "整理", "下载面板", "/console/downloads", ["download", "qb", "下载任务"]),
|
||||
page("organize", "整理", "整理记录", "/console/organize", ["organize", "入库", "历史"]),
|
||||
page("organize-attention", "整理", "需要处理的整理记录", "/console/organize?tab=records&attention=1", [
|
||||
"inbox",
|
||||
"待处理",
|
||||
"识别不到",
|
||||
"decision",
|
||||
]),
|
||||
page("files", "整理", "文件管理", "/console/files", ["files", "文件"]),
|
||||
page("trash", "整理", "回收站", "/console/files/trash", ["trash", "删除"]),
|
||||
page("library", "整理", "媒体库", "/console/library", ["library", "媒体库", "作品"]),
|
||||
|
||||
@@ -25,6 +25,7 @@ import { jsonb } from "../rows.ts";
|
||||
import { closeDecisions, type Exec, openDecision } from "./common.ts";
|
||||
import { ensureUnits } from "./entities.ts";
|
||||
import { type Layout, seasonOrigins } from "./episode-structure.ts";
|
||||
import { isEntityWatched } from "./watched.ts";
|
||||
|
||||
// 集数解析接入(docs/plan/episode-resolution.md 批次 2):识别绑定作品后、建集单元前,按作品季表 + 映射规则把
|
||||
// 「发布者声称的季集」换成「媒体库应当使用的季集」。判定本身在 domain resolveEpisodes,这里只装配数据与落库:
|
||||
@@ -405,6 +406,9 @@ export async function settleEpisodeDecision(
|
||||
: null;
|
||||
await detachFromEpisodeDecisions(ctx, exec, sourceReleaseId, target);
|
||||
if (!target) return;
|
||||
// 两层(2026-10-06):集数待确认是内部事项(供智能体调查,用户在订阅详情 / 作品页集数映射里看原因),
|
||||
// 只给关注中的作品开;不在关注范围的作品资源照样待确认(不建集、订阅跳过),进入关注范围补刷新时重算再开
|
||||
if (!(await isEntityWatched(exec, entityId))) return;
|
||||
|
||||
const existing = await exec
|
||||
.selectFrom("decision")
|
||||
|
||||
@@ -55,6 +55,7 @@ import {
|
||||
import { loadSubject, searchBangumi } from "./meta-subjects.ts";
|
||||
import { tmdbRecallInput, tmdbToCandidate } from "./tmdb-candidate.ts";
|
||||
import { loadRecognizeCache, type RecognizeMeta, recognizeMetaOf, saveRecognizeCache } from "./tmdb-recognize-cache.ts";
|
||||
import { enqueueWatchedRefresh, isEntityWatched } from "./watched.ts";
|
||||
|
||||
// resolveObservation:parseRelease → 本地召回(别名 pg_trgm + 已有外部身份 + 人工锁)→ [按需] TMDB 候选 → domain.resolveIdentity。
|
||||
// auto 才建/关联正式作品;ambiguous / no_match / 查询失败进待识别池(候选只存 JSON),有界退避复查。
|
||||
@@ -900,7 +901,14 @@ async function bindAuto(
|
||||
reason: resolution.reason,
|
||||
};
|
||||
});
|
||||
if (created) await enqueueNewEntityRefresh(ctx, created);
|
||||
// 两层(2026-10-06):自动新建的作品只在关注范围内才排刷新(用户搜索 / 手动识别 / 接管下载,或已被订阅等);
|
||||
// RSS / 列表扫进来、没人关心的作品不拉 TMDB 季表,等它进入关注范围(建订阅、搜索、开始下载)时再补排
|
||||
const userAsked = lookup === "search" || lookup === "manual" || lookup === "takeover";
|
||||
if (created) {
|
||||
if (userAsked || (await isEntityWatched(ctx.db, created))) await enqueueNewEntityRefresh(ctx, created);
|
||||
} else if (userAsked && result.mediaEntityId) {
|
||||
await enqueueWatchedRefresh(ctx, result.mediaEntityId, `lookup:${lookup}`);
|
||||
}
|
||||
return result;
|
||||
} catch (e) {
|
||||
if (e instanceof IdentityConflictError && attempt < 2) continue;
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import { sql } from "@umt/db";
|
||||
import type { ServerContext } from "../../types.ts";
|
||||
import type { Exec } from "./common.ts";
|
||||
|
||||
// 关注中的作品(2026-10-06,集数识别分两层):
|
||||
// 确定性的集数校验 / 换算对所有已绑定作品的资源照做(无外部请求、无打扰);
|
||||
// 有成本或会打扰的后续动作——拉 TMDB、自动新建作品后的元数据刷新、开集数待确认、派智能体——只对关注中的作品做。
|
||||
//
|
||||
// 关注中 = 满足任一:
|
||||
// 1. 有进行中的订阅(subscription.status in active / pending);
|
||||
// 2. 用户明确表达过兴趣:手动下载过(acquisition_plan.evaluation.manual = true)、用户搜索 / 手动识别出的资源
|
||||
// (source_release.resolution_evidence.lookup in search / manual)、人工 / 智能体确认的外部身份(evidence_level = manual);
|
||||
// 3. 正在下载或整理:未移除且没入库完的下载任务(直接、经资源或经下载计划关联),或排队 / 执行中的整理记录;
|
||||
// 4. 已在媒体库:有在用(active)的已入库文件。
|
||||
// RSS / 站点列表扫进来、自动建档却没人关心的作品不算。
|
||||
|
||||
const OPEN_SUBSCRIPTION = ["active", "pending"];
|
||||
const DOWNLOAD_DONE = ["imported", "removed"];
|
||||
|
||||
export async function isEntityWatched(exec: Exec, entityId: string): Promise<boolean> {
|
||||
const r = await sql<{ watched: boolean }>`
|
||||
select (
|
||||
exists (select 1 from subscription s where s.media_entity_id = ${entityId} and s.status = any(${OPEN_SUBSCRIPTION}))
|
||||
or exists (select 1 from media_asset a where a.media_entity_id = ${entityId} and a.status = 'active')
|
||||
or exists (select 1 from external_identity x
|
||||
where x.media_entity_id = ${entityId} and x.status = 'accepted' and x.evidence_level = 'manual')
|
||||
or exists (select 1 from source_release r
|
||||
where r.media_entity_id = ${entityId} and r.resolution_evidence->>'lookup' in ('search', 'manual'))
|
||||
or exists (select 1 from acquisition_plan p left join acquisition_slot sl on sl.id = p.slot_id
|
||||
where (sl.media_entity_id = ${entityId} or p.evaluation->>'mediaEntityId' = ${entityId}::text)
|
||||
and (p.evaluation->>'manual')::boolean is true)
|
||||
or exists (select 1 from download_task t
|
||||
left join source_release r on r.id = t.source_release_id
|
||||
left join acquisition_plan p on p.id = t.acquisition_plan_id
|
||||
left join acquisition_slot sl on sl.id = p.slot_id
|
||||
where t.removed_at is null and t.status <> all(${DOWNLOAD_DONE})
|
||||
and ${entityId} in (t.media_entity_id, r.media_entity_id, sl.media_entity_id))
|
||||
or exists (select 1 from organization_record o
|
||||
where o.media_entity_id = ${entityId} and o.status in ('queued', 'running'))
|
||||
) as watched`.execute(exec);
|
||||
return r.rows[0]?.watched === true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 作品进入关注范围(建订阅、用户搜索、开始下载)时补排一次 full 元数据刷新:只对从没刷新过的作品排
|
||||
* (自动建档时因不在关注范围而没排的),刷新完成会重算待确认 / 滞后放行资源的集数(必要时开集数待确认)。
|
||||
* 入队失败只记日志;同一作品同一原因只排一次(幂等键)。
|
||||
*/
|
||||
export async function enqueueWatchedRefresh(ctx: ServerContext, entityId: string, reason: string): Promise<boolean> {
|
||||
const e = await ctx.db
|
||||
.selectFrom("media_entity")
|
||||
.select(["id", "last_metadata_refresh_at", "status"])
|
||||
.where("id", "=", entityId)
|
||||
.executeTakeFirst();
|
||||
if (!e || e.last_metadata_refresh_at || e.status === "merged") return false;
|
||||
try {
|
||||
await ctx.engine.enqueue(
|
||||
"refreshMetadata",
|
||||
{ mediaEntityId: entityId, full: true },
|
||||
{ idempotencyKey: `refreshMetadata:watched:${entityId}`, traceId: entityId },
|
||||
);
|
||||
return true;
|
||||
} catch (err) {
|
||||
ctx.logger.debug(
|
||||
{ entityId, reason, err: { message: err instanceof Error ? err.message : String(err) } },
|
||||
"进入关注范围的元数据刷新入队失败",
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user