dsh-supermesh 0.0.4 → 0.0.6

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.
@@ -15,7 +15,7 @@ import { HTTPError, defineHandler, getQuery, getRouterParam, readBody } from "h3
15
15
  import { createStorage } from "unstorage";
16
16
  import fs from "unstorage/drivers/fs";
17
17
  import { homedir } from "node:os";
18
- import { ReasoningEffortId, createUserMessage } from "@deepseek-ai/dsh-llm";
18
+ import { ReasoningEffortId, boundContextSummary, createUserMessage, joinAssistantStreamText } from "@deepseek-ai/dsh-llm";
19
19
  import { access, lstat, mkdir, mkdtemp, realpath, rename, rm, writeFile } from "node:fs/promises";
20
20
  import { Session, SessionId } from "@deepseek-ai/dsh-session";
21
21
  import { realpathNormalize } from "@deepseek-ai/dsh-workspace";
@@ -1455,25 +1455,14 @@ var Worker = class Worker extends Model {
1455
1455
  }).where("id", "=", id).execute();
1456
1456
  }
1457
1457
  async reportProgress(id, reportState, report) {
1458
- return this.db.transaction().execute(async (trx) => {
1458
+ await this.db.transaction().execute(async (trx) => {
1459
1459
  const worker = await new Worker(trx).findById(id);
1460
1460
  if (!worker || worker.status === "ended") throw new Error("Worker 已结束或不存在");
1461
1461
  const ticket = await trx.selectFrom("ticket").selectAll().where("id", "=", worker.ticketId).executeTakeFirst();
1462
1462
  if (!ticket || ticket.status === "done" || ticket.status === "cancelled") throw new Error("工单已结束或不存在");
1463
1463
  const now = (/* @__PURE__ */ new Date()).toISOString();
1464
1464
  await new Worker(trx).setReport(id, reportState, report, now);
1465
- const message = await new Inbox(trx).enqueue({
1466
- type: "project",
1467
- projectId: ticket.projectId,
1468
- origin: "worker",
1469
- kind: "ticket",
1470
- ticketId: ticket.id,
1471
- workerId: id,
1472
- title: reportState,
1473
- message: report
1474
- });
1475
1465
  if (reportState === "ready") await new Ticket(trx).endOnReport(ticket.id, now);
1476
- return message;
1477
1466
  });
1478
1467
  }
1479
1468
  };
@@ -1546,6 +1535,33 @@ const { error } = await new Migrator({
1546
1535
  provider: new MigrationProvider(database, migrations)
1547
1536
  }).migrateToLatest();
1548
1537
  if (error) throw error;
1538
+ // src/channel/_shared/admission.ts
1539
+ /**
1540
+ * 准入只回答「这条消息能不能进流程」,强度回答「它算不算开工请求」。
1541
+ * 没 @ bot 的消息最多是 inferred 候选,只有管理员点名或已订阅话题上的跟进才是 explicit。
1542
+ */
1543
+ function channelTriggerStrength(input) {
1544
+ if (!input.human || input.historical && !input.subscribed) return null;
1545
+ if (input.subscribed) return input.admin ? "explicit" : input.inferred === "off" ? null : "inferred";
1546
+ if (!input.admin || input.ignored && !input.mentioned) return null;
1547
+ if (input.mentioned) return "explicit";
1548
+ return input.kind === "open" && input.inferred !== "off" ? "inferred" : null;
1549
+ }
1550
+ /** 已投递的触发按当前事实判强度,供收件箱与建票闸使用。 */
1551
+ function triggerStrengthOf(input) {
1552
+ return input.admin && (input.mentioned || input.subscribed) ? "explicit" : "inferred";
1553
+ }
1554
+ /** 建票闸:没有触发来源(人工建票)放行,inferred 候选只有 auto 模式才允许开票。 */
1555
+ function ticketAllowed(strength, inferred) {
1556
+ return strength !== "inferred" || inferred === "auto";
1557
+ }
1558
+ /**
1559
+ * 进流程不等于被点名。没 @ bot 的消息只是时间线记录:可以分诊,但不建票、不派工、也不在渠道上发言。
1560
+ * 只有明确 @、或者这条话题已经被票订阅(人在跟进已有任务)才算在跟 bot 说话。
1561
+ */
1562
+ function addressedToBot(input) {
1563
+ return input.mentioned || input.subscribed;
1564
+ }
1549
1565
  // src/channel/_shared/proxy.ts
1550
1566
  async function channelProxyEnvironment(url, inherited) {
1551
1567
  const env = { ...inherited };
@@ -1588,6 +1604,8 @@ var agent_model_catalog_get_default = defineHandler(async () => {
1588
1604
  return getServerContext(server).sessionController.modelCatalog();
1589
1605
  });
1590
1606
  const DSH_PLUGIN_HOME = `${process.env.DSH_HOME ?? join(homedir(), ".dsh")}/.supermesh`;
1607
+ /** 代理工作区:角色会话的 cwd 与官方工作区条目都只指向这里,插件状态留在上一层。 */
1608
+ const DSH_WORKSPACE_HOME = join(DSH_PLUGIN_HOME, "workspace");
1591
1609
  // src/storage/index.ts
1592
1610
  const storage = createStorage({ driver: fs({
1593
1611
  atomic: true,
@@ -1607,6 +1625,7 @@ const defaults = {
1607
1625
  supervisor: null
1608
1626
  },
1609
1627
  administrators: [],
1628
+ inferred: "observe",
1610
1629
  maxWorkers: 10,
1611
1630
  backgroundLimitMinutes: 30,
1612
1631
  autoMerge: false,
@@ -1676,6 +1695,7 @@ function valid(value, allowEmpty = false) {
1676
1695
  return entries.every(([key, entry]) => {
1677
1696
  if (key === "administrators") return Array.isArray(entry) && entry.length <= 100 && entry.every((name) => typeof name === "string" && /^[a-z0-9][\w.-]{0,254}$/i.test(name.trim()));
1678
1697
  if (key === "autoMerge" || key === "autoArchiveWorkers") return typeof entry === "boolean";
1698
+ if (key === "inferred") return entry === "off" || entry === "observe" || entry === "auto";
1679
1699
  if (key === "models") return validModels(entry);
1680
1700
  if (!Object.hasOwn(limits, key)) return false;
1681
1701
  const [min, max] = limits[key];
@@ -1717,7 +1737,9 @@ var agent_model_get_default = defineHandler(async () => (await setting.load()).m
1717
1737
  // src/service/role-model.ts
1718
1738
  const roleModel = defineService({
1719
1739
  async resolve(model) {
1720
- const value = await getServerContext(server).llm.resolveCallConfig({
1740
+ const llm = getServerContext(server).get("llm");
1741
+ if (!llm) throw new Error("llm_unavailable");
1742
+ const value = await llm.resolveCallConfig({
1721
1743
  provider: model.provider,
1722
1744
  model: model.model,
1723
1745
  ...model.reasoningEffort ? { reasoningEffort: ReasoningEffortId(model.reasoningEffort) } : {}
@@ -1766,7 +1788,7 @@ const roleModel = defineService({
1766
1788
  ];
1767
1789
  return () => disposers.forEach((dispose) => dispose());
1768
1790
  });
1769
- await ctx.sessionPersistence.flush();
1791
+ await getServerContext(server).get("sessionPersistence")?.flush();
1770
1792
  }
1771
1793
  });
1772
1794
  // src/server/routes/agent.model.patch.ts
@@ -1881,6 +1903,31 @@ singlet.stale = function stale() {
1881
1903
  singlet.drain = async function drain() {
1882
1904
  while (pending.size) await Promise.allSettled([...pending.values()].map((record) => record.promise));
1883
1905
  };
1906
+ // src/service/admission.ts
1907
+ async function admin(actorName) {
1908
+ const name = (actorName ?? "").toLowerCase();
1909
+ return name !== "" && (await setting.load()).administrators.some((entry) => entry.toLowerCase() === name);
1910
+ }
1911
+ /** 按触发自身的点名事实和话题订阅判强度;订阅状态每次现查,票可能在建票之后才挂上。 */
1912
+ async function triggerStrength(trigger) {
1913
+ const subscribed = (await db.ticketThread.listTicketIds(trigger.threadId)).length > 0;
1914
+ return triggerStrengthOf({
1915
+ mentioned: Boolean(trigger.mentioned),
1916
+ subscribed,
1917
+ admin: await admin(trigger.actorName)
1918
+ });
1919
+ }
1920
+ /** 建票闸用:指定 triggerId 时按那条触发判,否则取这些话题里最新的一条人类触发。 */
1921
+ async function latestTriggerStrength(threadIds, triggerId) {
1922
+ if (triggerId) {
1923
+ const trigger = await db.trigger.findById(triggerId);
1924
+ return trigger ? triggerStrength(trigger) : void 0;
1925
+ }
1926
+ const candidates = (await Promise.all(threadIds.map((id) => db.trigger.listByThread(id, 20)))).flat();
1927
+ const human = candidates.filter((row) => row.human === 1);
1928
+ const trigger = (human.length ? human : candidates).sort((left, right) => right.at.localeCompare(left.at))[0];
1929
+ return trigger ? triggerStrength(trigger) : void 0;
1930
+ }
1884
1931
  // src/service/session.ts
1885
1932
  const presets$1 = {
1886
1933
  main: "orchestrator",
@@ -1898,6 +1945,12 @@ const session = defineService({
1898
1945
  registered.delete(id);
1899
1946
  };
1900
1947
  },
1948
+ /** 同步判定一个 Agent 是不是插件的四个角色会话:只按预设判断,不读会话历史。 */
1949
+ roleOf(agent) {
1950
+ const preset = getServerContext(server).agentPresets.composedPreset(agent.ctx);
1951
+ if (!preset || !registered.has(preset)) return null;
1952
+ return Object.keys(presets$1).find((role) => presets$1[role] === preset) ?? null;
1953
+ },
1901
1954
  async attach(agent) {
1902
1955
  const ctx = getServerContext(server);
1903
1956
  const preset = ctx.agentPresets.composedPreset(agent.ctx);
@@ -2040,16 +2093,19 @@ const session = defineService({
2040
2093
  if (identity.workerId && (await db.worker.findById(id))?.status === "ended") throw new Error("worker_ended");
2041
2094
  const ctx = getServerContext(server);
2042
2095
  if (mode === "interrupt") await session.cancel(id, true);
2096
+ const live = ctx.agents.get(SessionId(id));
2097
+ const target = mode === "interrupt" ? "steer" : mode === "queue" || live?.status !== "running" ? "queue" : "steer";
2043
2098
  const admitted = await ctx.sessionController.prompt({
2044
2099
  sessionId: SessionId(id),
2045
2100
  requestId,
2046
- mode: mode === "interrupt" ? "steer" : "queue",
2101
+ mode: target,
2047
2102
  content: [{
2048
2103
  type: "text",
2049
2104
  text
2050
2105
  }]
2051
2106
  }, controller$2.signal);
2052
2107
  if (admitted && typeof admitted === "object" && "ok" in admitted && admitted.ok === false) throw new Error(`prompt_rejected: ${String(admitted.error ?? "unknown")}`);
2108
+ return requestId;
2053
2109
  }),
2054
2110
  async cancel(id, keepInbox = false) {
2055
2111
  (await resolveAgent(id)).cancel({
@@ -2079,8 +2135,10 @@ const session = defineService({
2079
2135
  };
2080
2136
  },
2081
2137
  workspace: singlet("session:workspace", async () => {
2082
- await mkdir(DSH_PLUGIN_HOME, { recursive: true });
2083
- return getServerContext(server).workspaceRegistry.create(DSH_PLUGIN_HOME, "代理工作区");
2138
+ const ctx = getServerContext(server);
2139
+ await mkdir(DSH_WORKSPACE_HOME, { recursive: true });
2140
+ await retireLegacyWorkspace(ctx);
2141
+ return ctx.workspaceRegistry.create(DSH_WORKSPACE_HOME, "代理工作区");
2084
2142
  }),
2085
2143
  activate: (id) => resolveAgent(id),
2086
2144
  async lookup(id) {
@@ -2144,6 +2202,15 @@ const session = defineService({
2144
2202
  if ((await session.activity(id)).background) throw new Error("background_stop_pending");
2145
2203
  }
2146
2204
  });
2205
+ /**
2206
+ * 旧版本把「代理工作区」注册在 `.supermesh` 根本身,那里同时存着插件状态。
2207
+ * 工作区路径不可改,只能删掉这条注册;目录与会话日志都保留,旧会话退化为未分组。
2208
+ */
2209
+ async function retireLegacyWorkspace(ctx) {
2210
+ const legacy = await realpathNormalize(DSH_PLUGIN_HOME).catch(() => void 0);
2211
+ if (!legacy) return;
2212
+ for (const workspace of ctx.workspaceRegistry.list()) if (workspace.path === legacy) await ctx.workspaceRegistry.delete(workspace.id).catch(() => void 0);
2213
+ }
2147
2214
  async function bindWorkspace(id, cwd) {
2148
2215
  const ctx = getServerContext(server);
2149
2216
  const sid = SessionId(id);
@@ -2151,6 +2218,7 @@ async function bindWorkspace(id, cwd) {
2151
2218
  if (!directory) return;
2152
2219
  const actual = await realpathNormalize(directory).catch(() => void 0);
2153
2220
  if (!actual) return;
2221
+ if (actual === await realpathNormalize(DSH_PLUGIN_HOME).catch(() => void 0)) return;
2154
2222
  for (const workspace of [await session.workspace(), ...ctx.workspaceRegistry.list()]) {
2155
2223
  if (workspace.sessionIds.includes(sid)) return;
2156
2224
  if (workspace.path !== actual) continue;
@@ -2200,7 +2268,22 @@ const inbox = defineService({
2200
2268
  if (!identity) return null;
2201
2269
  const scope = scopeOf(identity);
2202
2270
  if (!scope) return null;
2203
- const messages = await db.inbox.listScoped(scope, includeChannel);
2271
+ const rows = await db.inbox.listScoped(scope, includeChannel);
2272
+ const triggers = /* @__PURE__ */ new Map();
2273
+ for (const triggerId of new Set(rows.map((message) => message.triggerId).filter(Boolean))) {
2274
+ const trigger = await db.trigger.findById(triggerId);
2275
+ if (trigger) triggers.set(triggerId, {
2276
+ kind: trigger.kind,
2277
+ actorName: trigger.actorName,
2278
+ human: Boolean(trigger.human),
2279
+ mentioned: Boolean(trigger.mentioned),
2280
+ strength: await triggerStrength(trigger)
2281
+ });
2282
+ }
2283
+ const messages = rows.map((message) => ({
2284
+ ...message,
2285
+ ...message.triggerId && triggers.has(message.triggerId) ? { trigger: triggers.get(message.triggerId) } : {}
2286
+ }));
2204
2287
  const projects = (await db.project.listAll()).filter((project) => project.enabled && (identity.role === "main" || project.id === identity.projectId)).map(({ id, name, directory, remoteUrl }) => ({
2205
2288
  id,
2206
2289
  name,
@@ -2291,11 +2374,14 @@ const inbox = defineService({
2291
2374
  continue;
2292
2375
  }
2293
2376
  if ((await session.activity(id)).running || stopped$2) continue;
2377
+ const trigger = message.triggerId ? await db.trigger.findById(message.triggerId) : void 0;
2378
+ const strength = trigger ? await triggerStrength(trigger) : void 0;
2294
2379
  await session.send(id, [
2295
2380
  message.title ?? "",
2296
2381
  `[Inbox ${message.id}]`,
2297
2382
  message.triggerId ? `triggerId: ${message.triggerId}` : "",
2298
2383
  message.threadId ? `threadId: ${message.threadId}` : "",
2384
+ trigger ? `actor: ${trigger.actorName ?? "unknown"} human: ${trigger.human ? "yes" : "no"} mentioned: ${trigger.mentioned ? "yes" : "no"} strength: ${strength}` : "",
2299
2385
  message.message
2300
2386
  ].filter(Boolean).join(String.fromCharCode(10)), "queue", requestId);
2301
2387
  await db.inbox.resetDelivery(message.id);
@@ -2404,7 +2490,7 @@ var ask__id__answer_post_default = defineHandler(async (event) => {
2404
2490
  const directory = join(DSH_PLUGIN_HOME, "cli");
2405
2491
  const bin = join(directory, "bin");
2406
2492
  const gitconfig = join(directory, "gitconfig");
2407
- const removed = [
2493
+ const tokens = [
2408
2494
  "GH_TOKEN",
2409
2495
  "GITHUB_TOKEN",
2410
2496
  "GH_ENTERPRISE_TOKEN",
@@ -2412,23 +2498,16 @@ const removed = [
2412
2498
  "GITLAB_TOKEN",
2413
2499
  "GLAB_TOKEN",
2414
2500
  "OAUTH_TOKEN",
2415
- "CI_JOB_TOKEN",
2416
- "GIT_DIR",
2417
- "GIT_WORK_TREE",
2418
- "GIT_INDEX_FILE",
2419
- "GIT_PREFIX",
2420
- "GIT_COMMON_DIR",
2421
- "GIT_OBJECT_DIRECTORY",
2422
- "GIT_ALTERNATE_OBJECT_DIRECTORIES",
2423
- "GIT_NAMESPACE",
2424
- "GIT_CONFIG_COUNT",
2425
- "GIT_CONFIG_PARAMETERS",
2501
+ "CI_JOB_TOKEN"
2502
+ ];
2503
+ const identities = [
2426
2504
  "GIT_AUTHOR_NAME",
2427
2505
  "GIT_AUTHOR_EMAIL",
2428
2506
  "GIT_COMMITTER_NAME",
2429
- "GIT_COMMITTER_EMAIL",
2430
- "SSH_ASKPASS"
2507
+ "GIT_COMMITTER_EMAIL"
2431
2508
  ];
2509
+ /** 角色会话标记:由 `ctx.shellEnv` 按调用会话注入,shim 只在这个变量存在时才切到 bot 身份。 */
2510
+ const ROLE_MARKER = "DSH_SUPERMESH_ROLE";
2432
2511
  let restore;
2433
2512
  let writing$1 = Promise.resolve();
2434
2513
  let basePath = "";
@@ -2437,21 +2516,22 @@ const shell = defineService({
2437
2516
  if (restore) throw new Error("shell_already_started");
2438
2517
  basePath = (process.env.PATH ?? "").split(delimiter).filter((path) => resolve(path).toLowerCase() !== resolve(bin).toLowerCase()).join(delimiter);
2439
2518
  await refresh();
2440
- const values = {
2441
- ...Object.fromEntries(removed.map((key) => [key, void 0])),
2442
- PATH: [bin, basePath].join(delimiter),
2443
- GIT_CONFIG_GLOBAL: gitconfig,
2444
- GIT_CONFIG_NOSYSTEM: "1",
2445
- GIT_ASKPASS: "",
2446
- GIT_TERMINAL_PROMPT: "0"
2447
- };
2448
- const previous = Object.fromEntries(Object.keys(values).map((key) => [key, process.env[key]]));
2449
- const apply = (entries) => {
2450
- for (const [key, value] of Object.entries(entries)) if (value === void 0) delete process.env[key];
2451
- else process.env[key] = value;
2519
+ const release = getServerContext(server).get("shellEnv")?.register({
2520
+ name: "supermesh-role",
2521
+ variables: { DSH_SUPERMESH_ROLE: { description: "Supermesh 角色会话标记,决定 gh / glab / git 是否使用插件的机器人身份。" } },
2522
+ resolve: (execution) => {
2523
+ const agent = execution.agent;
2524
+ const role = agent ? session.roleOf(agent) : null;
2525
+ return role ? { DSH_SUPERMESH_ROLE: role } : {};
2526
+ }
2527
+ });
2528
+ const previous = process.env.PATH;
2529
+ process.env.PATH = [bin, basePath].join(delimiter);
2530
+ restore = () => {
2531
+ release?.();
2532
+ if (previous === void 0) delete process.env.PATH;
2533
+ else process.env.PATH = previous;
2452
2534
  };
2453
- apply(values);
2454
- restore = () => apply(previous);
2455
2535
  return async () => {
2456
2536
  const release = restore;
2457
2537
  restore = void 0;
@@ -2460,10 +2540,7 @@ const shell = defineService({
2460
2540
  };
2461
2541
  },
2462
2542
  commandEnvironment() {
2463
- return {
2464
- ...process.env,
2465
- ...restore ? { PATH: basePath } : {}
2466
- };
2543
+ return { ...process.env };
2467
2544
  },
2468
2545
  refresh() {
2469
2546
  if (!restore) return Promise.resolve();
@@ -2503,32 +2580,43 @@ async function refresh() {
2503
2580
  git_protocol: "https"
2504
2581
  } } : {}
2505
2582
  }));
2583
+ const shellPath = shellPathOf(basePath);
2506
2584
  for (const cli of ["gh", "glab"]) {
2507
2585
  const executable = await nativeCli(cli);
2508
2586
  const configKey = cli === "gh" ? "GH_CONFIG_DIR" : "GLAB_CONFIG_DIR";
2509
2587
  const hostKey = cli === "gh" ? "GH_HOST" : "GITLAB_HOST";
2510
2588
  const host = cli === "gh" ? "github.com" : gitlabHost;
2511
- const shellPath = shellPathOf(basePath);
2512
2589
  const keyringKeys = cli === "glab" ? ["GLAB_USE_KEYRING"] : [];
2513
- await own(join(bin, cli), [
2514
- "#!/bin/sh",
2515
- `unset ${removed.filter((key) => /TOKEN/.test(key)).join(" ")}`,
2590
+ const botEnv = [
2591
+ ...tokens.map((key) => `unset ${key}`),
2516
2592
  `export PATH=${quote(shellPath)}`,
2517
2593
  `export ${configKey}=${quote(join(directory, cli).replaceAll("\\", "/"))}`,
2518
2594
  `export ${hostKey}=${quote(host)}`,
2519
- ...keyringKeys.map((key) => `export ${key}=false`),
2595
+ ...keyringKeys.map((key) => `export ${key}=false`)
2596
+ ];
2597
+ await own(join(bin, cli), [
2598
+ "#!/bin/sh",
2599
+ `if [ -z "$${ROLE_MARKER}" ]; then exec ${executable ? quote(executable.replaceAll("\\", "/")) : "exit 127"} "$@"; fi`,
2600
+ ...botEnv,
2520
2601
  executable ? `exec ${quote(executable.replaceAll("\\", "/"))} "$@"` : `echo '${cli} is not installed' >&2; exit 127`,
2521
2602
  ""
2522
2603
  ].join("\n"), 448);
2523
2604
  const cmd = (value) => value.replaceAll("%", "%%");
2524
- await own(join(bin, `${cli}.cmd`), [
2525
- "@echo off",
2526
- "setlocal",
2527
- ...removed.filter((key) => /TOKEN/.test(key)).map((key) => `set "${key}="`),
2605
+ const botCmd = [
2606
+ ...tokens.map((key) => `set "${key}="`),
2528
2607
  `set "PATH=${cmd(basePath)}"`,
2529
2608
  `set "${configKey}=${cmd(join(directory, cli))}"`,
2530
2609
  `set "${hostKey}=${host}"`,
2531
- ...keyringKeys.map((key) => `set "${key}=false"`),
2610
+ ...keyringKeys.map((key) => `set "${key}=false"`)
2611
+ ];
2612
+ await own(join(bin, `${cli}.cmd`), [
2613
+ "@echo off",
2614
+ "setlocal",
2615
+ `if not defined ${ROLE_MARKER} goto plain`,
2616
+ ...botCmd,
2617
+ executable ? `"${cmd(executable)}" %*` : `echo ${cli} is not installed 1>&2 & exit /b 127`,
2618
+ "exit /b %errorlevel%",
2619
+ ":plain",
2532
2620
  executable ? `"${cmd(executable)}" %*` : `echo ${cli} is not installed 1>&2 & exit /b 127`,
2533
2621
  "exit /b %errorlevel%",
2534
2622
  ""
@@ -2538,25 +2626,61 @@ async function refresh() {
2538
2626
  const escaping = [
2539
2627
  "GH_CONFIG_DIR",
2540
2628
  "GH_HOST",
2541
- ...removed.filter((key) => /TOKEN/.test(key))
2629
+ ...tokens
2542
2630
  ];
2543
2631
  await own(join(bin, "gh-default"), [
2544
2632
  "#!/bin/sh",
2545
- `unset ${escaping.join(" ")}`,
2546
- `export PATH=${quote(shellPathOf(basePath))}`,
2633
+ `if [ -z "$${ROLE_MARKER}" ]; then exec ${nativeGh ? quote(nativeGh.replaceAll("\\", "/")) : "exit 127"} "$@"; fi`,
2634
+ ...escaping.map((key) => `unset ${key}`),
2635
+ `export PATH=${quote(shellPath)}`,
2547
2636
  nativeGh ? `exec ${quote(nativeGh.replaceAll("\\", "/"))} "$@"` : "echo gh is not installed >&2; exit 127",
2548
2637
  ""
2549
2638
  ].join("\n"), 448);
2550
2639
  await own(join(bin, "gh-default.cmd"), [
2551
2640
  "@echo off",
2552
2641
  "setlocal",
2642
+ `if not defined ${ROLE_MARKER} goto plain`,
2553
2643
  ...escaping.map((key) => `set "${key}="`),
2554
2644
  `set "PATH=${basePath.replaceAll("%", "%%")}"`,
2555
2645
  nativeGh ? `"${nativeGh.replaceAll("%", "%%")}" %*` : "echo gh is not installed 1>&2 & exit /b 127",
2556
2646
  "exit /b %errorlevel%",
2647
+ ":plain",
2648
+ nativeGh ? `"${nativeGh.replaceAll("%", "%%")}" %*` : "echo gh is not installed 1>&2 & exit /b 127",
2649
+ "exit /b %errorlevel%",
2557
2650
  ""
2558
2651
  ].join("\r\n"), 448);
2652
+ const nativeGit = await nativeCli("git");
2559
2653
  const gitQuote = (value) => JSON.stringify(value);
2654
+ const gitEnv = [
2655
+ ...identities.map((key) => `unset ${key}`),
2656
+ `export GIT_CONFIG_GLOBAL=${quote(gitconfig.replaceAll("\\", "/"))}`,
2657
+ "export GIT_CONFIG_NOSYSTEM=1",
2658
+ "export GIT_ASKPASS=",
2659
+ "export GIT_TERMINAL_PROMPT=0"
2660
+ ];
2661
+ await own(join(bin, "git"), [
2662
+ "#!/bin/sh",
2663
+ `if [ -z "$${ROLE_MARKER}" ]; then exec ${nativeGit ? quote(nativeGit.replaceAll("\\", "/")) : "exit 127"} "$@"; fi`,
2664
+ ...gitEnv,
2665
+ nativeGit ? `exec ${quote(nativeGit.replaceAll("\\", "/"))} "$@"` : "echo git is not installed >&2; exit 127",
2666
+ ""
2667
+ ].join("\n"), 448);
2668
+ await own(join(bin, "git.cmd"), [
2669
+ "@echo off",
2670
+ "setlocal",
2671
+ `if not defined ${ROLE_MARKER} goto plain`,
2672
+ ...identities.map((key) => `set "${key}="`),
2673
+ `set "GIT_CONFIG_GLOBAL=${gitconfig.replaceAll("%", "%%")}"`,
2674
+ "set \"GIT_CONFIG_NOSYSTEM=1\"",
2675
+ "set \"GIT_ASKPASS=\"",
2676
+ "set \"GIT_TERMINAL_PROMPT=0\"",
2677
+ nativeGit ? `"${nativeGit.replaceAll("%", "%%")}" %*` : "echo git is not installed 1>&2 & exit /b 127",
2678
+ "exit /b %errorlevel%",
2679
+ ":plain",
2680
+ nativeGit ? `"${nativeGit.replaceAll("%", "%%")}" %*` : "echo git is not installed 1>&2 & exit /b 127",
2681
+ "exit /b %errorlevel%",
2682
+ ""
2683
+ ].join("\r\n"), 448);
2560
2684
  const cliPath = (cli) => quote(join(bin, cli).replaceAll("\\", "/"));
2561
2685
  const lines = [
2562
2686
  "[user]",
@@ -2682,14 +2806,14 @@ const devops = defineService({
2682
2806
  },
2683
2807
  save(kind, patch) {
2684
2808
  return channel.serialize(() => save(kind, patch)).then(async (view) => {
2685
- const { shell } = await import("./shell-DzrnBk4C.js");
2809
+ const { shell } = await import("./shell-BZBvr4aJ.js");
2686
2810
  await shell.refresh();
2687
2811
  return view;
2688
2812
  });
2689
2813
  },
2690
2814
  removeCredentials(kind) {
2691
2815
  return channel.serialize(() => removeCredentials(kind)).then(async (view) => {
2692
- const { shell } = await import("./shell-DzrnBk4C.js");
2816
+ const { shell } = await import("./shell-BZBvr4aJ.js");
2693
2817
  await shell.refresh();
2694
2818
  return view;
2695
2819
  });
@@ -3951,6 +4075,42 @@ const archive = defineService({ async session(id) {
3951
4075
  const eventQueues = /* @__PURE__ */ new Map();
3952
4076
  let stopped = false;
3953
4077
  let observing = false;
4078
+ const finish = singlet((current) => `worker:finish:${current.id}`, async (current, reason) => {
4079
+ const worker = await db.worker.findById(current.id);
4080
+ if (!worker || worker.status === "ended") return;
4081
+ const asks = (await db.inbox.listByTicket(worker.ticketId)).filter((message) => message.kind === "ask" && message.workerId === worker.id);
4082
+ if (!reason) {
4083
+ if (asks.some((message) => message.status === "pending")) {
4084
+ await deferWhileWaiting(worker);
4085
+ return;
4086
+ }
4087
+ const answered = asks.filter((message) => message.answer);
4088
+ if (answered.length) {
4089
+ const receipts = await session.receipts(worker.id);
4090
+ if (answered.some((message) => !receipts.some((receipt) => receipt.requestId === `supermesh:answer:${message.id}`))) {
4091
+ await deferWhileWaiting(worker);
4092
+ return;
4093
+ }
4094
+ }
4095
+ }
4096
+ if (stopped) return;
4097
+ const now = (/* @__PURE__ */ new Date()).toISOString();
4098
+ await db.worker.setBackgroundUntil(worker.id, null);
4099
+ await db.worker.end(worker.id, reason ?? (worker.reportState === "failed" ? "failed" : "completed"), now);
4100
+ const ticket = await db.ticket.findById(worker.ticketId);
4101
+ if (ticket && ticket.status !== "done" && ticket.status !== "cancelled") {
4102
+ if (ticket.prState === "merged" || ticket.prState === "closed") await finishTicket(ticket.id, "done", now, now);
4103
+ else if (!reason && worker.reportState === "dropped") await finishTicket(ticket.id, "done", now, now);
4104
+ else await db.ticket.update(ticket.id, {
4105
+ status: !reason && worker.reportState === "ready" ? "review" : "waiting",
4106
+ updatedAt: now
4107
+ });
4108
+ }
4109
+ const ended = await db.ticket.findById(worker.ticketId);
4110
+ if (!reason && worker.reportState !== "failed" && ended && (ended.status === "done" || ended.status === "cancelled")) await archiveWorker(worker.id);
4111
+ if (ended && (ended.status === "done" || ended.status === "cancelled")) await releaseDependents(ended.id);
4112
+ await notifyRouter(worker, reason);
4113
+ });
3954
4114
  const worker = defineService({
3955
4115
  start() {
3956
4116
  if (singlet.busy("worker:slots") || eventQueues.size) throw new Error("worker_busy");
@@ -3967,7 +4127,15 @@ const worker = defineService({
3967
4127
  for (const worker of await db.worker.listRunning()) {
3968
4128
  if (stopped) break;
3969
4129
  const ticket = await db.ticket.findById(worker.ticketId);
3970
- if (!ticket || ticket.status === "done" || ticket.status === "cancelled") continue;
4130
+ if (!ticket) {
4131
+ await db.worker.end(worker.id, "stopped", (/* @__PURE__ */ new Date()).toISOString());
4132
+ continue;
4133
+ }
4134
+ if (ticket.status === "done" || ticket.status === "cancelled") {
4135
+ await session.send(worker.id, `票 ${ticket.id} 已${ticket.status === "done" ? "完成" : "取消"},本次授权已收回:立即停手,不要再提交、推送或开 PR。`, "interrupt").catch(() => void 0);
4136
+ await db.worker.end(worker.id, "stopped", (/* @__PURE__ */ new Date()).toISOString());
4137
+ continue;
4138
+ }
3971
4139
  if (ticket.prState === "merged" || ticket.prState === "closed") {
3972
4140
  const now = (/* @__PURE__ */ new Date()).toISOString();
3973
4141
  await db.worker.end(worker.id, "stopped", now);
@@ -4074,7 +4242,8 @@ const worker = defineService({
4074
4242
  })}`,
4075
4243
  "来源话题:",
4076
4244
  ...sources,
4077
- worker.recoveryNote ?? ""
4245
+ worker.recoveryNote ?? "",
4246
+ "你的最后一条消息会原样转给项目编排。"
4078
4247
  ].filter(Boolean).join(String.fromCharCode(10));
4079
4248
  const now = (/* @__PURE__ */ new Date()).toISOString();
4080
4249
  await db.worker.start(worker.id, now);
@@ -4205,6 +4374,7 @@ const worker = defineService({
4205
4374
  if (!observing || stopped || event.type !== "turn/end") return;
4206
4375
  const previous = eventQueues.get(source.id) ?? Promise.resolve();
4207
4376
  const action = () => stopped ? Promise.resolve() : (async () => {
4377
+ if (event.data.reason.kind === "aborted" && event.data.reason.reason.kind === "hook" && event.data.reason.reason.reason === "supermesh_cancel") return;
4208
4378
  const identity = await session.resolve(source.id);
4209
4379
  if (!identity || identity.role !== "worker" || !identity.workerId) return;
4210
4380
  const current = await db.worker.findById(identity.workerId);
@@ -4225,39 +4395,6 @@ const worker = defineService({
4225
4395
  return current;
4226
4396
  })
4227
4397
  });
4228
- async function finish(current, reason) {
4229
- const asks = (await db.inbox.listByTicket(current.ticketId)).filter((message) => message.kind === "ask" && message.workerId === current.id);
4230
- if (!reason) {
4231
- if (asks.some((message) => message.status === "pending")) {
4232
- await deferWhileWaiting(current);
4233
- return;
4234
- }
4235
- const answered = asks.filter((message) => message.answer);
4236
- if (answered.length) {
4237
- const receipts = await session.receipts(current.id);
4238
- if (answered.some((message) => !receipts.some((receipt) => receipt.requestId === `supermesh:answer:${message.id}`))) {
4239
- await deferWhileWaiting(current);
4240
- return;
4241
- }
4242
- }
4243
- }
4244
- if (stopped) return;
4245
- const now = (/* @__PURE__ */ new Date()).toISOString();
4246
- await db.worker.setBackgroundUntil(current.id, null);
4247
- await db.worker.end(current.id, reason ?? (current.reportState === "failed" ? "failed" : "completed"), now);
4248
- const ticket = await db.ticket.findById(current.ticketId);
4249
- if (ticket && ticket.status !== "done" && ticket.status !== "cancelled") {
4250
- if (ticket.prState === "merged" || ticket.prState === "closed") await finishTicket(ticket.id, "done", now, now);
4251
- else if (!reason && current.reportState === "dropped") await finishTicket(ticket.id, "done", now, now);
4252
- else await db.ticket.update(ticket.id, {
4253
- status: !reason && current.reportState === "ready" ? "review" : "waiting",
4254
- updatedAt: now
4255
- });
4256
- }
4257
- const ended = await db.ticket.findById(current.ticketId);
4258
- if (!reason && current.reportState !== "failed" && ended && (ended.status === "done" || ended.status === "cancelled")) await archiveWorker(current.id);
4259
- if (ended && (ended.status === "done" || ended.status === "cancelled")) await releaseDependents(ended.id);
4260
- }
4261
4398
  async function blockedByDependency(ticketId) {
4262
4399
  const links = await db.ticketLink.listDependsOn(ticketId);
4263
4400
  if (!links.length) return false;
@@ -4313,14 +4450,75 @@ async function deferWhileWaiting(current) {
4313
4450
  if (!ticket || ticket.status === "done" || ticket.status === "cancelled") return;
4314
4451
  const now = (/* @__PURE__ */ new Date()).toISOString();
4315
4452
  await db.worker.end(current.id, "completed", now);
4316
- if (ticket.prState === "merged") {
4317
- await finishTicket(ticket.id, "done", now, now);
4318
- return;
4319
- }
4320
- await db.ticket.update(ticket.id, {
4453
+ if (ticket.prState === "merged") await finishTicket(ticket.id, "done", now, now);
4454
+ else await db.ticket.update(ticket.id, {
4321
4455
  status: "waiting",
4322
4456
  updatedAt: now
4323
4457
  });
4458
+ await notifyRouter(current);
4459
+ }
4460
+ function settlementSummary(name, stopReason) {
4461
+ const subject = `Worker ${name}`;
4462
+ if (stopReason === "completed") return `${subject} finished. It cannot receive follow-up messages.`;
4463
+ if (stopReason === "aborted") return `${subject} was stopped before it finished.`;
4464
+ return `${subject} failed before it finished.`;
4465
+ }
4466
+ /** 官方结算只带子级最后一条非空 assistant 消息;没有正文时用流式拼接兜底。 */
4467
+ async function closingText(id) {
4468
+ const { events } = await session.history(id);
4469
+ let message = [];
4470
+ let streamed = "";
4471
+ for (const event of events) if (event.type === "assistant/message") {
4472
+ const content = event.data.message.content;
4473
+ if (content.length > 0) message = content.flatMap((part) => part.type === "text" && part.text.length > 0 ? [part.text] : []);
4474
+ streamed += joinAssistantStreamText(event.data.stream);
4475
+ } else if (event.type === "assistant/attempt") streamed += joinAssistantStreamText(event.data.stream);
4476
+ return message.length ? message : streamed ? [streamed] : [];
4477
+ }
4478
+ /**
4479
+ * Worker 是独立根会话,不在官方 subagent 树里,拿不到官方的结算通知。
4480
+ * 这里按官方结算的形状补一条:同一条消息、同一个 source.form,编排在跑就 steer,空闲就 followup。
4481
+ * 编排不在线也投:先激活会话再送,官方是直接丢掉。
4482
+ */
4483
+ async function notifyRouter(current, reason) {
4484
+ try {
4485
+ const ticket = await db.ticket.findById(current.ticketId);
4486
+ if (!ticket) return;
4487
+ const project = await db.project.findById(ticket.projectId);
4488
+ if (!project?.enabled) return;
4489
+ const existing = project.orchestratorSessionId;
4490
+ const id = existing && await session.resolve(existing).then(Boolean, () => false) ? existing : await session.create("project", { projectId: project.id });
4491
+ const agent = await session.activate(id);
4492
+ const stopReason = reason === "failed" ? "error" : reason === "stopped" ? "aborted" : "completed";
4493
+ const summary = settlementSummary(ticket.id, stopReason);
4494
+ const closing = await closingText(current.id);
4495
+ const message = createUserMessage({
4496
+ content: [{
4497
+ type: "text",
4498
+ text: summary
4499
+ }, ...closing.length === 0 ? [{
4500
+ type: "text",
4501
+ text: "It left no closing message."
4502
+ }] : [{
4503
+ type: "text",
4504
+ text: "Its closing message:"
4505
+ }, ...closing.map((text) => ({
4506
+ type: "text",
4507
+ text
4508
+ }))]],
4509
+ source: {
4510
+ kind: "subagent-settled",
4511
+ form: "notice",
4512
+ summary: boundContextSummary(summary),
4513
+ stopReason,
4514
+ senderSessionId: current.id
4515
+ }
4516
+ });
4517
+ if (agent.status === "idle") agent.followup(message);
4518
+ else agent.steer(message);
4519
+ } catch (error) {
4520
+ getServerContext(server).logger.warn("supermesh: worker %s settlement notice failed: %s", current.id, error instanceof Error ? error.message : String(error));
4521
+ }
4324
4522
  }
4325
4523
  async function archiveWorker(id) {
4326
4524
  await archive.session(id);
@@ -4743,4 +4941,4 @@ function readMetadata(raw) {
4743
4941
  providerId: "providerId" in value && typeof value.providerId === "string" ? value.providerId : ""
4744
4942
  };
4745
4943
  }
4746
- export { project as a, shell as c, singlet as d, setting as f, db as g, channelProxyEnvironment as h, archive as i, inbox as l, DSH_PLUGIN_HOME as m, server as n, worktree as o, defineService as p, worker as r, devops as s, channel as t, session as u };
4944
+ export { addressedToBot as _, project as a, db as b, shell as c, latestTriggerStrength as d, singlet as f, channelProxyEnvironment as g, DSH_PLUGIN_HOME as h, archive as i, inbox as l, defineService as m, server as n, worktree as o, setting as p, worker as r, devops as s, channel as t, session as u, channelTriggerStrength as v, ticketAllowed as y };