agent-loft 0.2.76 → 0.2.78

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/src/core/hub.ts CHANGED
@@ -26,9 +26,11 @@ import {
26
26
  updateAgentBinding,
27
27
  updateConversation,
28
28
  type Conversation,
29
+ requestedPermission,
29
30
  } from "./store.js";
30
31
  import { attachmentInfo, ensureUploadsDir, KIND_LABEL } from "./uploads.js";
31
32
  import { memoryOwnerOf, sessionMemory } from "./personal.js";
33
+ import { exceedsPermission, minPermission, PERMISSION_LABEL, permissionCapOfAccess, permissionOfSandbox, type PermissionLevel } from "./permission.js";
32
34
  import { readMemory } from "./memory.js";
33
35
  import { getUser, userEvents } from "./users.js";
34
36
  import type {
@@ -164,12 +166,18 @@ export type ConversationInfo = {
164
166
  usage?: UsageTotals;
165
167
  busy: boolean;
166
168
  activeAt: number;
169
+ /** 当前上下文已闲置过期;直接发消息会自动换新,打开历史本身不会续期。 */
170
+ idleExpired: boolean;
167
171
  createdAt: number;
168
172
  hidden?: boolean;
169
173
  /** 从哪条对话分叉出来的 */
170
174
  forkOf?: string;
171
175
  /** 当前 agent 能不能从某条回复处分叉成新对话 */
172
176
  canFork?: boolean;
177
+ /** 这条对话实际的权限级别(没选过就是引擎默认对应的那一级) */
178
+ permission: PermissionLevel;
179
+ /** 这条对话最高能选到哪一级 */
180
+ permissionMax: PermissionLevel;
173
181
  /** 这条对话的专家 */
174
182
  expert: ExpertBadge;
175
183
  /** 这条对话有主人、会用上主人的记忆(主人自己关了记忆的话实际不会注入,见 personal.ts) */
@@ -612,10 +620,13 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
612
620
  })(),
613
621
  busy: this.isBusy(key),
614
622
  activeAt: conv.activeAt,
623
+ idleExpired: !!(binding.sessionId || binding.forkFrom) && isExpired(conv),
615
624
  createdAt: conv.createdAt,
616
625
  ...(conv.hidden ? { hidden: true } : {}),
617
626
  ...(conv.forkOf ? { forkOf: conv.forkOf } : {}),
618
627
  ...(this.drivers.get(conv.agent)?.forkAt ? { canFork: true } : {}),
628
+ permission: this.permissionOf(conv),
629
+ permissionMax: this.permissionMax(conv),
619
630
  expert: this.expertBadge(conv),
620
631
  ...(memoryOwnerOf(conv) ? { personal: true } : {}),
621
632
  ...(conv.taskId ? { taskId: conv.taskId } : {}),
@@ -705,6 +716,7 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
705
716
  // 自定义专家只给它选中的
706
717
  const builtin = !expert && isBuiltin(agent) ? builtinAgentSession(taskOwner, agent) : {};
707
718
  const skills = expert ? sessionSkills(taskOwner, expert.skills) : builtin.skills;
719
+ const permission = this.effectivePermission(conv);
708
720
  const session = driver.createSession(
709
721
  {
710
722
  cwd: conv.cwd,
@@ -713,7 +725,8 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
713
725
  ...(effort ? { effort } : {}),
714
726
  ...(resumeId ? { resumeId } : {}),
715
727
  ...(fork ? { fork: true } : {}),
716
- ...(conv.autoEdit ? { autoEdit: true } : {}),
728
+ ...(permission ? { permission } : {}),
729
+ ...(taskOwner && getUser(taskOwner)?.role !== "admin" ? { noSessionGrant: true } : {}),
717
730
  ...(expert ? { expert } : {}),
718
731
  ...(memory ? { memory } : {}),
719
732
  ...(taskOwner ? { tasks: { userId: taskOwner, convKey: key } } : {}),
@@ -1220,6 +1233,7 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
1220
1233
  const conv = getConversation(key)!;
1221
1234
  await this.drop(key, "已开新会话");
1222
1235
  this.markSwitched(key, op.seq);
1236
+ this.clearFullPermission(key);
1223
1237
  updateAgentBinding(key, conv.agent, { sessionId: undefined, forkFrom: undefined, model: model || undefined, effort: undefined });
1224
1238
  this.emitEvent(key, { type: "meta" });
1225
1239
  const runtime = await this.runtimeNow(key);
@@ -1235,6 +1249,7 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
1235
1249
  if (!current) return "当前还没有可分叉的会话。";
1236
1250
  await this.drop(key, "已分叉会话");
1237
1251
  this.markSwitched(key, op.seq);
1252
+ this.clearFullPermission(key);
1238
1253
  // 只记下意图,下一条消息时才真正分叉(见 session() 里的 pendingFork)
1239
1254
  updateAgentBinding(key, conv.agent, { forkFrom: current });
1240
1255
  touchConversation(key);
@@ -1322,26 +1337,121 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
1322
1337
  return `思考程度已切换为 ${effort}。`;
1323
1338
  }
1324
1339
 
1325
- /** /autoedit:on 不给就是切换。只影响正在跑的会话和以后新建的,不追溯已经弹出的授权。 */
1326
- private async setAutoEditNow(key: string, on: boolean | undefined): Promise<string> {
1340
+ // ---------- 权限级别 ----------
1341
+
1342
+ /**
1343
+ * 这条对话最高能到哪一级。谁发的都一样,看的是对话的主人和专家:
1344
+ * - 完全允许只给主人是管理员的对话。飞书群聊、没绑定的私聊没有主人(群里谁都能说话),最高自动改文件;
1345
+ * - 不超过专家的权限(专家被删了按最低算);
1346
+ * - 不是管理员的话,Codex 也不能超过设置里的沙箱:管理员收紧了沙箱,成员不能自己放开。
1347
+ */
1348
+ permissionMax(conv: Conversation): PermissionLevel {
1349
+ const owner = memoryOwnerOf(conv);
1350
+ const admin = !!owner && getUser(owner)?.role === "admin";
1351
+ const access = conv.expert ? (getExpert(conv.expert)?.access ?? "web") : "exec";
1352
+ const max = minPermission(admin ? "full" : "edit", permissionCapOfAccess(access));
1353
+ return !admin && conv.agent === "codex" ? minPermission(max, permissionOfSandbox(config().agents.codex.sandbox)) : max;
1354
+ }
1355
+
1356
+ /** 交给 session 的级别:选过的按上限封顶;没选过就是 undefined,走引擎默认 */
1357
+ private effectivePermission(conv: Conversation): PermissionLevel | undefined {
1358
+ const wanted = requestedPermission(conv);
1359
+ return wanted ? minPermission(wanted, this.permissionMax(conv)) : undefined;
1360
+ }
1361
+
1362
+ /** 给人看的级别:没选过就换算引擎默认(Claude 逐次询问,Codex 看设置里的沙箱,不超过专家) */
1363
+ permissionOf(conv: Conversation): PermissionLevel {
1364
+ const effective = this.effectivePermission(conv);
1365
+ if (effective) return effective;
1366
+ if (conv.agent !== "codex") return "ask";
1367
+ const access = conv.expert ? (getExpert(conv.expert)?.access ?? "web") : "exec";
1368
+ return minPermission(permissionOfSandbox(config().agents.codex.sandbox), permissionCapOfAccess(access));
1369
+ }
1370
+
1371
+ /**
1372
+ * 记下级别并告诉活着的会话,同步完成(定时任务到点时紧接着就要发消息)。
1373
+ * 不追溯已经弹出的授权:授权卡里还有新建定时任务这类不属于这个开关的确认。
1374
+ */
1375
+ private applyPermission(key: string, level: PermissionLevel | undefined): void {
1376
+ updateConversation(key, { permission: level, autoEdit: undefined });
1327
1377
  const conv = getConversation(key)!;
1328
- const next = on ?? !conv.autoEdit;
1329
1378
  const live = this.live.get(key);
1330
- if (live?.session.setAutoEdit) await withTimeout(live.session.setAutoEdit(next), "切换自动改文件");
1331
- updateConversation(key, { autoEdit: next });
1379
+ live?.session.setPermission?.(this.effectivePermission(conv))?.catch((err) => {
1380
+ // 切换没生效(比如调低时 CLI 没响应):不能让它带着旧权限继续,空闲下来就按新级别重新拉起
1381
+ console.warn(`[${conv.agent}] ${key} 切换权限失败:`, err instanceof Error ? err.message : err);
1382
+ this.staleLive.add(live.id);
1383
+ this.dropIfStale(key);
1384
+ });
1332
1385
  this.emitEvent(key, { type: "meta" });
1333
- const driver = this.requireDriver(conv.agent);
1334
- const note =
1335
- conv.agent === "codex"
1336
- ? `\n\n注意:${driver.label} 改文件由沙箱控制(设置 → Agent → 沙箱),这个开关只对 Claude 生效。`
1337
- : "";
1338
- return next
1339
- ? `已开启:这条对话里 Claude 修改工作目录(${conv.cwd})内的文件不再询问;目录外的文件、Bash 命令照常询问。发 /autoedit off 关闭。${note}`
1340
- : `已关闭:改文件恢复逐次询问。${note}`;
1386
+ }
1387
+
1388
+ /** 开新会话时「完全允许」不留:放手是对那一次任务说的,不是对这条对话以后所有的事 */
1389
+ private clearFullPermission(key: string): void {
1390
+ const conv = getConversation(key);
1391
+ if (conv && requestedPermission(conv) === "full") updateConversation(key, { permission: undefined });
1392
+ }
1393
+
1394
+ /**
1395
+ * 定时任务的专用对话:级别以任务为准(到点时、改了任务、任务不再用这条对话时调)。
1396
+ * 返回封顶后实际生效的级别。
1397
+ */
1398
+ applyTaskPermission(key: string, level: PermissionLevel | undefined): PermissionLevel | undefined {
1399
+ const conv = getConversation(key);
1400
+ if (!conv) return undefined;
1401
+ if (requestedPermission(conv) !== level) this.applyPermission(key, level);
1402
+ return this.effectivePermission(getConversation(key)!);
1403
+ }
1404
+
1405
+ private describePermission(key: string): string {
1406
+ const conv = getConversation(key)!;
1407
+ return [
1408
+ `当前权限:${PERMISSION_LABEL[this.permissionOf(conv)]}。`,
1409
+ "",
1410
+ "- `/permission ask`:逐次询问",
1411
+ "- `/permission edit`:自动改文件",
1412
+ "- `/permission full`:完全允许",
1413
+ "- `/permission default`:恢复默认",
1414
+ "",
1415
+ `这条对话最高能到「${PERMISSION_LABEL[this.permissionMax(conv)]}」。`,
1416
+ ].join("\n");
1417
+ }
1418
+
1419
+ private permissionDone(conv: Conversation, level: PermissionLevel | undefined): string {
1420
+ const nextTurn = conv.agent === "codex" ? "下一轮起生效。" : "";
1421
+ if (!level) return `已恢复默认:${PERMISSION_LABEL[this.permissionOf(conv)]}。${nextTurn}`;
1422
+ if (level === "full") {
1423
+ return `⚠️ 已切换为「完全允许」:agent 的操作不再询问,可以跑任意命令、改任意文件。提问和标了「调用前询问」的 MCP 照常询问;开新会话后恢复默认。${nextTurn}`;
1424
+ }
1425
+ if (level === "ask") return `已切换为「逐次询问」:改文件、跑命令都要先问你。${nextTurn}`;
1426
+ return conv.agent === "codex"
1427
+ ? `已切换为「自动改文件」:工作目录(${conv.cwd})内可以直接改文件、跑命令,超出沙箱的要先问你。${nextTurn}`
1428
+ : `已切换为「自动改文件」:修改工作目录(${conv.cwd})内的文件不再询问;目录外的文件、Bash 命令照常询问。`;
1429
+ }
1430
+
1431
+ private setPermissionNow(key: string, level: PermissionLevel | undefined, allowFull: boolean): string {
1432
+ const conv = getConversation(key)!;
1433
+ if (conv.taskId) return "这是定时任务的专用对话,权限跟着任务走。到定时任务页面编辑这个任务来改。";
1434
+ if (level === "full" && !allowFull) return "只有管理员本人能选「完全允许」。飞书上要在私聊里、并且绑定了管理员账号。";
1435
+ const max = this.permissionMax(conv);
1436
+ if (level && exceedsPermission(level, max)) return `这条对话最高只能到「${PERMISSION_LABEL[max]}」(看对话的主人和专家的权限)。`;
1437
+ this.applyPermission(key, level);
1438
+ return this.permissionDone(getConversation(key)!, level);
1439
+ }
1440
+
1441
+ /** level 不给就是恢复默认。allowFull:操作的人是不是管理员本人(渠道核过的) */
1442
+ setPermission(key: string, level: PermissionLevel | undefined, allowFull: boolean): Promise<string> {
1443
+ return this.serial(key, async () => this.setPermissionNow(key, level, allowFull));
1444
+ }
1445
+
1446
+ /** /autoedit:on 不给就是切换。「自动改文件」的旧叫法,关掉就是恢复默认 */
1447
+ private setAutoEditNow(key: string, on: boolean | undefined): string {
1448
+ const conv = getConversation(key)!;
1449
+ const next = on ?? requestedPermission(conv) !== "edit";
1450
+ return this.setPermissionNow(key, next ? "edit" : undefined, false);
1341
1451
  }
1342
1452
 
1343
1453
  setAutoEdit(key: string, on?: boolean): Promise<string> {
1344
- return this.serial(key, () => this.setAutoEditNow(key, on));
1454
+ return this.serial(key, async () => this.setAutoEditNow(key, on));
1345
1455
  }
1346
1456
 
1347
1457
  // ---------- 记忆变了 / 主人变了 ----------
@@ -1427,6 +1537,7 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
1427
1537
  this.markSwitched(key, op.seq);
1428
1538
  // 新会话:所有 agent 的旧会话都不接着用(专家换了,上下文里的人设、权限都不对了)
1429
1539
  updateConversation(key, { agent: hit.engine, expert: isBuiltin(hit.id) ? undefined : hit.id, perAgent: {} });
1540
+ this.clearFullPermission(key);
1430
1541
  this.emitEvent(key, { type: "meta" });
1431
1542
  return `已换成专家「${hit.label}」,开了新会话。`;
1432
1543
  }
@@ -1612,7 +1723,7 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
1612
1723
  `目录:${conv.cwd}`,
1613
1724
  `模型:${runtime.model ?? "默认"}`,
1614
1725
  ...(runtime.effort ? [`思考程度:${runtime.effort}`] : []),
1615
- ...(conv.autoEdit ? ["自动允许改文件:开(/autoedit off 关闭)"] : []),
1726
+ `权限:${PERMISSION_LABEL[this.permissionOf(conv)]}(/permission 切换)`,
1616
1727
  ...(extra.length > 0 ? ["", ...extra] : []),
1617
1728
  ].join("\n");
1618
1729
  }
@@ -1669,7 +1780,8 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
1669
1780
  title: `${conv.title ?? "会话"} · 分叉`.slice(0, 80),
1670
1781
  cwd: conv.cwd,
1671
1782
  ...(conv.cwdExplicit ? { cwdExplicit: true } : {}),
1672
- ...(conv.autoEdit ? { autoEdit: true } : {}),
1783
+ // 「完全允许」不跟着分叉过去
1784
+ ...(requestedPermission(conv) === "edit" ? { permission: "edit" as const } : {}),
1673
1785
  ...(conv.expert ? { expert: conv.expert } : {}),
1674
1786
  forkOf: key,
1675
1787
  perAgent: {
@@ -1732,6 +1844,8 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
1732
1844
  convVisible?: (convKey: string) => boolean;
1733
1845
  /** 多用户:false = 不能点会落盘的「总是允许」(见 InteractionSpec.alwaysGlobal) */
1734
1846
  allowGlobalAlways?: boolean;
1847
+ /** 发命令的人能不能把对话调成「完全允许」。不给就是不能:只有确认是管理员本人的渠道才给 */
1848
+ allowFullAccess?: boolean;
1735
1849
  },
1736
1850
  ): Promise<CommandReply> {
1737
1851
  const text = (t: string): CommandReply => ({ type: "text", text: t });
@@ -1754,6 +1868,8 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
1754
1868
  return text(getConversation(key)!.cwd);
1755
1869
  case "autoedit":
1756
1870
  return text(await this.setAutoEdit(key, cmd.on));
1871
+ case "permission":
1872
+ return text(cmd.level ? await this.setPermission(key, cmd.level === "default" ? undefined : cmd.level, ctx.allowFullAccess === true) : this.describePermission(key));
1757
1873
  case "status":
1758
1874
  return text(await this.status(key));
1759
1875
  case "cd":
@@ -0,0 +1,42 @@
1
+ // 对话的权限级别:agent 干活时哪些操作要先问用户。两个引擎共用同一套级别(映射见各自的 session.ts):
2
+ //
3
+ // ask 逐次询问 Claude:default; Codex:只读沙箱(写文件要批准)
4
+ // edit 自动改文件 Claude:acceptEdits; Codex:工作区可写沙箱
5
+ // full 完全允许 Claude:default + 全放行;Codex:无沙箱 + 全放行
6
+ //
7
+ // 不选级别(undefined)= 老行为:Claude 逐次询问,Codex 按设置里的沙箱。老对话、老任务都不受影响。
8
+ //
9
+ // 完全允许不用 Claude 的 bypassPermissions:那会让 canUseTool 变成死代码,提问卡和「调用前询问」的 MCP 都走不到。
10
+ // Codex 也不用 approvalPolicy: never:实测 on-request 配无沙箱一样不弹审批,还留着 MCP 审批这条路。
11
+ import type { ExpertAccess } from "./experts.js";
12
+
13
+ export const PERMISSION_LEVELS = ["ask", "edit", "full"] as const;
14
+ export type PermissionLevel = (typeof PERMISSION_LEVELS)[number];
15
+
16
+ export const PERMISSION_LABEL: Record<PermissionLevel, string> = {
17
+ ask: "逐次询问",
18
+ edit: "自动改文件",
19
+ full: "完全允许",
20
+ };
21
+
22
+ export function isPermissionLevel(v: unknown): v is PermissionLevel {
23
+ return typeof v === "string" && (PERMISSION_LEVELS as readonly string[]).includes(v);
24
+ }
25
+
26
+ export function minPermission(a: PermissionLevel, b: PermissionLevel): PermissionLevel {
27
+ return PERMISSION_LEVELS.indexOf(a) <= PERMISSION_LEVELS.indexOf(b) ? a : b;
28
+ }
29
+
30
+ export function exceedsPermission(level: PermissionLevel, max: PermissionLevel): boolean {
31
+ return PERMISSION_LEVELS.indexOf(level) > PERMISSION_LEVELS.indexOf(max);
32
+ }
33
+
34
+ /** 专家的权限决定它最高能到哪一级:不能跑命令的放开「全部允许」也没有意义,Codex 的沙箱也不能超过它 */
35
+ export function permissionCapOfAccess(access: ExpertAccess): PermissionLevel {
36
+ return access === "exec" ? "full" : access === "edit" ? "edit" : "ask";
37
+ }
38
+
39
+ /** 设置里的 Codex 沙箱换算成级别:显示「现在实际是哪一级」、给成员定上限时用 */
40
+ export function permissionOfSandbox(sandbox: string): PermissionLevel {
41
+ return sandbox === "danger-full-access" ? "full" : sandbox === "read-only" ? "ask" : "edit";
42
+ }
package/src/core/store.ts CHANGED
@@ -6,6 +6,7 @@
6
6
  import path from "node:path";
7
7
  import { config } from "./config.js";
8
8
  import { sql, transaction } from "./db.js";
9
+ import type { PermissionLevel } from "./permission.js";
9
10
 
10
11
  export type AgentBinding = {
11
12
  /** agent 侧的会话 id(Claude 的 sessionId / Codex 的 threadId) */
@@ -46,7 +47,12 @@ export type Conversation = {
46
47
  createdAt: number;
47
48
  /** Web 列表里隐藏(Web 上删除的会话只是隐藏,agent 侧的历史还在) */
48
49
  hidden?: boolean;
49
- /** /autoedit:这条对话里 agent 在工作目录内改文件不再询问(跨 /new 保留,属于对话不属于某个会话) */
50
+ /**
51
+ * 权限级别(见 permission.ts),属于对话不属于某个会话。没选过就没有。
52
+ * 「自动改文件」跨 /new 保留,「完全允许」开新会话时清掉。实际生效的还要封顶,见 hub.permissionMax。
53
+ */
54
+ permission?: PermissionLevel;
55
+ /** 以前 /autoedit 记的,只读不写(Claude 下等于 permission: "edit");选过级别就清掉 */
50
56
  autoEdit?: boolean;
51
57
  /** 从哪条对话分叉出来的(对话 key),列表里据此显示关联 */
52
58
  forkOf?: string;
@@ -158,6 +164,11 @@ function reconcileCwd(conv: Conversation): Conversation {
158
164
  return conv;
159
165
  }
160
166
 
167
+ /** 这条对话选的权限级别,兼容以前 /autoedit 记的。没选过就是 undefined */
168
+ export function requestedPermission(conv: Pick<Conversation, "permission" | "autoEdit" | "agent">): PermissionLevel | undefined {
169
+ return conv.permission ?? (conv.autoEdit && conv.agent === "claude" ? "edit" : undefined);
170
+ }
171
+
161
172
  export function getConversation(key: string): Conversation | undefined {
162
173
  const conv = load()[key];
163
174
  return conv ? reconcileCwd(conv) : undefined;
@@ -10,6 +10,7 @@ import { resolveWorkspacePath } from "./config.js";
10
10
  import { canUseExpert, getExpert } from "./experts.js";
11
11
  import { hub, type TaskTurnEnd } from "./hub.js";
12
12
  import { interactions, isDetached } from "./interactions.js";
13
+ import { PERMISSION_LABEL } from "./permission.js";
13
14
  import { memoryOwnerOf } from "./personal.js";
14
15
  import { getConversation, updateAgentBinding, updateConversation, type Conversation } from "./store.js";
15
16
  import { formatDateTime } from "./task-schedule.js";
@@ -142,7 +143,12 @@ function fire(task: Task, manual: boolean, now = Date.now()): string | undefined
142
143
  return undefined;
143
144
  }
144
145
  waiting.delete(task.id);
145
- const run = pushRun(task, { id: runId(), at: now, status: "running", convKey: key, ...(manual ? { note: "手动运行" } : {}) });
146
+ // 专用对话的权限以任务为准;发到已有对话的跟着那条对话,不动它。
147
+ // 每次都核一遍:主人被降级、专家权限改了,就按新的上限跑,并在运行记录里说一声
148
+ const permission = task.target.kind === "dedicated" ? hub.applyTaskPermission(key, task.permission) : undefined;
149
+ const capped = task.target.kind === "dedicated" && task.permission && permission !== task.permission ? `权限只能到「${PERMISSION_LABEL[permission ?? "ask"]}」,按这一级运行` : "";
150
+ const note = [manual ? "手动运行" : "", capped].filter(Boolean).join(";");
151
+ const run = pushRun(task, { id: runId(), at: now, status: "running", convKey: key, ...(note ? { note } : {}) });
146
152
  running.set(task.id, { runId: run.id, key, at: now });
147
153
  console.log(`[定时任务] ${task.id}「${task.title}」${manual ? "手动运行" : "到点运行"},发到 ${key}`);
148
154
  hub.send(
@@ -201,17 +207,20 @@ export function isTaskRunning(id: string): boolean {
201
207
  return running.has(id) || waiting.has(id);
202
208
  }
203
209
 
210
+ /** 对话不再是这个任务的专用对话:历史留着,任务给的权限收回(不能留一条完全允许的普通对话) */
211
+ export function releaseTaskConv(taskId: string, key: string): void {
212
+ const conv = getConversation(key);
213
+ if (conv?.taskId !== taskId) return;
214
+ hub.applyTaskPermission(key, undefined);
215
+ updateConversation(key, { taskId: undefined });
216
+ hub.emitEvent(key, { type: "meta" });
217
+ }
218
+
204
219
  /** 任务删了:它的专用对话留着(里面有历史),只是不再是谁的专用对话 */
205
220
  export function forgetTask(task: Task): void {
206
221
  waiting.delete(task.id);
207
222
  running.delete(task.id);
208
- if (task.target.kind === "dedicated" && task.target.key) {
209
- const conv = getConversation(task.target.key);
210
- if (conv?.taskId === task.id) {
211
- updateConversation(conv.key, { taskId: undefined });
212
- hub.emitEvent(conv.key, { type: "meta" });
213
- }
214
- }
223
+ if (task.target.kind === "dedicated" && task.target.key) releaseTaskConv(task.id, task.target.key);
215
224
  }
216
225
 
217
226
  export function startTaskRunner(): void {
@@ -11,6 +11,7 @@ import net from "node:net";
11
11
  import path from "node:path";
12
12
  import { config } from "./config.js";
13
13
  import { hub } from "./hub.js";
14
+ import { PERMISSION_LABEL, type PermissionLevel } from "./permission.js";
14
15
  import { interactions } from "./interactions.js";
15
16
  import { memoryOwnerOf } from "./personal.js";
16
17
  import { expertIdOf, getConversation } from "./store.js";
@@ -66,7 +67,19 @@ async function confirm(convKey: string, title: string, detail: string): Promise<
66
67
  return outcome.settlement === "allow-once" || outcome.settlement === "allow-always" || outcome.settlement === "allow-session";
67
68
  }
68
69
 
69
- function card(fields: { schedule?: TaskSchedule; notify?: string; where?: string; expert?: string; prompt?: string; enabled?: boolean }, now: number): string {
70
+ /** 这个任务跑起来是什么权限;完全允许要明说:改提示词、重新启用,等于让 agent 下次无人值守地做这些事 */
71
+ function permissionLine(level: PermissionLevel | undefined, follow: boolean): string {
72
+ if (level === "full") return `⚠️ 这个任务${follow ? "跟随的对话现在是" : "以"}「完全允许」${follow ? ",到点运行时" : "运行,"}不会再询问任何操作`;
73
+ return follow && level ? `跟随对话(现在是「${PERMISSION_LABEL[level]}」)` : level ? PERMISSION_LABEL[level] : "默认";
74
+ }
75
+
76
+ function taskPermissionLine(task: Task): string {
77
+ if (task.target.kind === "dedicated") return permissionLine(task.permission, false);
78
+ const conv = getConversation(task.target.key);
79
+ return permissionLine(conv ? hub.permissionOf(conv) : undefined, true);
80
+ }
81
+
82
+ function card(fields: { schedule?: TaskSchedule; notify?: string; where?: string; expert?: string; permission?: string; prompt?: string; enabled?: boolean }, now: number): string {
70
83
  const lines: string[] = [];
71
84
  if (fields.schedule) {
72
85
  const next = nextRun(fields.schedule, now);
@@ -76,6 +89,7 @@ function card(fields: { schedule?: TaskSchedule; notify?: string; where?: string
76
89
  if (fields.notify) lines.push(`**提醒**:${fields.notify === "always" ? "每次都提醒" : "有需要才提醒(由 agent 判断)"}`);
77
90
  if (fields.where) lines.push(`**结果发到**:${fields.where}`);
78
91
  if (fields.expert) lines.push(`**专家**:${fields.expert}`);
92
+ if (fields.permission) lines.push(`**权限**:${fields.permission}`);
79
93
  if (fields.enabled !== undefined) lines.push(`**状态**:${fields.enabled ? "恢复运行" : "暂停"}`);
80
94
  if (fields.prompt) lines.push("", "**到点要做的事**:", "", ...fields.prompt.split("\n").map((l) => `> ${l}`));
81
95
  return lines.join("\n");
@@ -126,7 +140,18 @@ async function call(userId: string, convKey: string, tool: string, args: Record<
126
140
  const ok = await confirm(
127
141
  convKey,
128
142
  `新建定时任务「${title}」`,
129
- card({ schedule, notify: String(input.notify), where: dedicated ? "单独开一条对话" : "这条对话", ...(dedicated ? { expert: expertName } : {}), prompt }, now),
143
+ card(
144
+ {
145
+ schedule,
146
+ notify: String(input.notify),
147
+ where: dedicated ? "单独开一条对话" : "这条对话",
148
+ ...(dedicated ? { expert: expertName } : {}),
149
+ // agent 建的专用对话任务一律从默认开始,要放宽只能用户到页面上改
150
+ permission: dedicated ? "默认(要放宽到定时任务页面上改)" : permissionLine(hub.permissionOf(conv), true),
151
+ prompt,
152
+ },
153
+ now,
154
+ ),
130
155
  );
131
156
  if (!ok) return fail("用户没有同意,任务没有建。");
132
157
  try {
@@ -179,6 +204,7 @@ async function call(userId: string, convKey: string, tool: string, args: Record<
179
204
  {
180
205
  ...(patch.schedule ? { schedule: patch.schedule as TaskSchedule } : {}),
181
206
  ...(patch.notify !== undefined ? { notify: String(patch.notify) } : {}),
207
+ permission: taskPermissionLine(task),
182
208
  ...(patch.enabled !== undefined ? { enabled: patch.enabled === true } : {}),
183
209
  ...(patch.prompt !== undefined ? { prompt: String(patch.prompt) } : {}),
184
210
  },
package/src/core/tasks.ts CHANGED
@@ -11,6 +11,7 @@ import { EventEmitter } from "node:events";
11
11
  import { dataDir, readJson, writeJsonAtomic } from "../home.js";
12
12
  import { describeSchedule, nextRun, normalizeSchedule, type TaskSchedule } from "./task-schedule.js";
13
13
  import { canUseExpert, getExpert, isBuiltin } from "./experts.js";
14
+ import { isPermissionLevel, type PermissionLevel } from "./permission.js";
14
15
 
15
16
  /**
16
17
  * 结果回到哪:
@@ -48,6 +49,8 @@ export type Task = {
48
49
  cwd?: string;
49
50
  model?: string;
50
51
  effort?: string;
52
+ /** 专用对话的权限级别(见 permission.ts):只有用户在页面上能设。没有就是引擎默认 */
53
+ permission?: PermissionLevel;
51
54
  enabled: boolean;
52
55
  createdAt: number;
53
56
  updatedAt: number;
@@ -140,6 +143,8 @@ export type TaskInput = {
140
143
  cwd?: unknown;
141
144
  model?: unknown;
142
145
  effort?: unknown;
146
+ /** 只有网页接口会给:agent 的工具(tasks-bridge.ts)不开放这个参数,免得 agent 给自己提权 */
147
+ permission?: unknown;
143
148
  enabled?: unknown;
144
149
  };
145
150
 
@@ -165,6 +170,13 @@ function cleanExpert(owner: string, v: unknown): { agent: string; expert?: strin
165
170
  return { agent: getExpert(id)!.engine, expert: id };
166
171
  }
167
172
 
173
+ function cleanPermission(v: unknown): PermissionLevel | undefined {
174
+ const s = str(v);
175
+ if (!s) return undefined;
176
+ if (!isPermissionLevel(s)) throw new Error("权限级别不对");
177
+ return s;
178
+ }
179
+
168
180
  function cleanTarget(v: unknown, prev?: TaskTarget): TaskTarget {
169
181
  const r = (v ?? {}) as Record<string, unknown>;
170
182
  if (r.kind === "conv" && typeof r.key === "string" && r.key) return { kind: "conv", key: r.key };
@@ -177,6 +189,8 @@ export function createTask(owner: string, input: TaskInput, by: "user" | "agent"
177
189
  const prompt = cleanPrompt(input.prompt);
178
190
  const schedule = normalizeSchedule(input.schedule, now);
179
191
  const picked = cleanExpert(owner, input.expert ?? input.agent);
192
+ // agent 建的一律从默认开始:要放宽得用户自己到页面上改
193
+ const permission = by === "user" ? cleanPermission(input.permission) : undefined;
180
194
  const task: Task = {
181
195
  id: `t_${crypto.randomBytes(5).toString("hex")}`,
182
196
  owner,
@@ -189,6 +203,7 @@ export function createTask(owner: string, input: TaskInput, by: "user" | "agent"
189
203
  ...(str(input.cwd) ? { cwd: str(input.cwd) } : {}),
190
204
  ...(str(input.model) ? { model: str(input.model) } : {}),
191
205
  ...(str(input.effort) ? { effort: str(input.effort) } : {}),
206
+ ...(permission ? { permission } : {}),
192
207
  enabled: input.enabled !== false,
193
208
  createdAt: now,
194
209
  updatedAt: now,
@@ -227,6 +242,11 @@ export function updateTask(owner: string, id: string, patch: TaskInput, now = Da
227
242
  if (str(patch[k])) next[k] = str(patch[k]);
228
243
  else delete next[k];
229
244
  }
245
+ if (patch.permission !== undefined) {
246
+ const permission = cleanPermission(patch.permission);
247
+ if (permission) next.permission = permission;
248
+ else delete next.permission;
249
+ }
230
250
  if (patch.enabled !== undefined) next.enabled = patch.enabled !== false;
231
251
  // 专用对话的专家 / 目录变了:旧的那条对话对不上了(对话中途不能换专家),下次新开一条
232
252
  if (
package/src/core/types.ts CHANGED
@@ -2,6 +2,7 @@
2
2
  // 之间只通过这里的类型说话。渠道不认识 Claude,agent 不认识飞书。
3
3
  import type { AgentCommand } from "./command-catalog.js";
4
4
  import type { ExpertRuntime } from "./experts.js";
5
+ import type { PermissionLevel } from "./permission.js";
5
6
 
6
7
  // ---------- 用户输入 ----------
7
8
 
@@ -207,8 +208,10 @@ export type SessionOptions = {
207
208
  fork?: boolean;
208
209
  /** 附件所在目录,agent 需要能直接读 */
209
210
  uploadsDir: string;
210
- /** 工作目录内改文件不再询问(/autoedit)。Bash 等照常询问 */
211
- autoEdit?: boolean;
211
+ /** 权限级别(见 core/permission.ts),已按主人和专家封顶。不给 = 老行为:Claude 逐次询问,Codex 按设置里的沙箱 */
212
+ permission?: PermissionLevel | undefined;
213
+ /** 不给「本会话全部允许」按钮:有主人的对话,主人不是管理员 */
214
+ noSessionGrant?: boolean;
212
215
  /**
213
216
  * 自定义专家(core/experts.ts):提示词、权限、技能、MCP、子智能体都按它来。
214
217
  * 不给就是内置专家:原装提示词和工具,技能与 MCP 按账号的内置默认配置加载。
@@ -267,8 +270,8 @@ export interface AgentSession {
267
270
  /** 手上已知的模型 / 思考程度,同步返回:不拉起进程、不发请求 */
268
271
  peekRuntime?(): RuntimeInfo;
269
272
  dispose(): Promise<void>;
270
- /** 运行中切换「自动允许改文件」;不支持的 agent 不实现 */
271
- setAutoEdit?(on: boolean): Promise<void>;
273
+ /** 运行中切换权限级别。不追溯已经弹出的授权 */
274
+ setPermission?(level: PermissionLevel | undefined): Promise<void>;
272
275
  }
273
276
 
274
277
  export type Diagnosis = {
@@ -479,3 +479,49 @@ textarea.sending {
479
479
  color: var(--fg-soft);
480
480
  margin-left: 6px;
481
481
  }
482
+
483
+ /* 权限按钮:完全允许要一眼看得出来 */
484
+ .perm-slot {
485
+ display: inline-flex;
486
+ min-width: 0;
487
+ }
488
+
489
+ .perm-pill {
490
+ display: inline-flex;
491
+ align-items: center;
492
+ gap: 4px;
493
+ height: 32px;
494
+ padding: 0 8px;
495
+ border-radius: 999px;
496
+ font-size: 13px;
497
+ color: var(--fg-faint);
498
+ white-space: nowrap;
499
+ }
500
+
501
+ .perm-pill:hover {
502
+ background: var(--bg-hover);
503
+ color: var(--fg);
504
+ }
505
+
506
+ .perm-pill svg {
507
+ width: 13px;
508
+ height: 13px;
509
+ flex-shrink: 0;
510
+ }
511
+
512
+ .perm-pill.danger,
513
+ .perm-pill.danger:hover {
514
+ color: var(--danger);
515
+ font-weight: 500;
516
+ }
517
+
518
+ .popover.perm-pop {
519
+ min-width: 260px;
520
+ }
521
+
522
+ @media (max-width: 480px) {
523
+ /* 窄屏只留盾牌,把地方让给模型按钮;完全允许仍然保留文字 */
524
+ .perm-pill:not(.danger) .perm-name {
525
+ display: none;
526
+ }
527
+ }
@@ -186,6 +186,22 @@
186
186
  margin: 0;
187
187
  }
188
188
 
189
+ .idle-session-continue {
190
+ border: 0;
191
+ padding: 0;
192
+ background: none;
193
+ color: inherit;
194
+ font: inherit;
195
+ text-decoration: underline;
196
+ text-underline-offset: 3px;
197
+ cursor: pointer;
198
+ }
199
+
200
+ .idle-session-continue:disabled {
201
+ opacity: .5;
202
+ cursor: wait;
203
+ }
204
+
189
205
  .error-box {
190
206
  border: 1px solid var(--danger);
191
207
  color: var(--danger);
package/web/css/tasks.css CHANGED
@@ -503,3 +503,7 @@ button.task-run:hover {
503
503
  font-size: 21px;
504
504
  }
505
505
  }
506
+
507
+ .task-perm-full {
508
+ color: var(--danger);
509
+ }
@@ -225,9 +225,10 @@
225
225
  height: 24px;
226
226
  }
227
227
 
228
- .ec-avatar img {
229
- width: 40px;
230
- height: 40px;
228
+ /* 压过后加载的 .expert-avatar img 默认尺寸,让上传头像填满信息卡圆框。 */
229
+ .ec-avatar.expert-avatar img {
230
+ width: 100%;
231
+ height: 100%;
231
232
  }
232
233
 
233
234
  .ec-avatar.expert-emoji {
package/web/lib/dom.js CHANGED
@@ -26,6 +26,7 @@ export function fill(el, ...kids) {
26
26
  }
27
27
 
28
28
  export const ICON = {
29
+ shield: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 3 5 6v5c0 4.4 2.9 8.3 7 10 4.1-1.7 7-5.6 7-10V6Z"/></svg>',
29
30
  menu: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M4 6h16M4 12h16M4 18h16"/></svg>',
30
31
  edit: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20h9"/><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z"/></svg>',
31
32
  compose: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H6a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-5"/><path d="M18.4 2.6a2 2 0 0 1 2.9 2.9L12.5 14.3 9 15l.7-3.5Z"/></svg>',