@teammy/server 0.2.17 → 0.2.19

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.
Files changed (30) hide show
  1. package/README.md +1 -1
  2. package/dist/main.js +735 -382
  3. package/dist/web/assets/Assistant-BAhJ1B8n.js +1 -0
  4. package/dist/web/assets/Computers-CBnQX-2p.css +1 -0
  5. package/dist/web/assets/Computers-hHQYztG9.js +13 -0
  6. package/dist/web/assets/{Conversation-Bu7mdJTX.js → Conversation-Bdsoobmv.js} +1 -1
  7. package/dist/web/assets/{Dashboard-B0Ojad36.js → Dashboard-De-8jlcE.js} +1 -1
  8. package/dist/web/assets/Dropdown-Dh9Q9fSi.js +55 -0
  9. package/dist/web/assets/Files-DYc1q61J.js +1 -0
  10. package/dist/web/assets/{Help-woS0MfLI.js → Help-DHZAzK6c.js} +59 -34
  11. package/dist/web/assets/{Markdown-DJ7qHSXM.js → Markdown-Gk89fXoh.js} +4 -4
  12. package/dist/web/assets/{MessageComposer-CkyAV-iI.js → MessageComposer-DFvWZibH.js} +1 -1
  13. package/dist/web/assets/ResourceLibrary-DYwZzWyh.js +6 -0
  14. package/dist/web/assets/{TerminalPane-qvAQ5u5W.js → TerminalPane-ZhM38vie.js} +2 -2
  15. package/dist/web/assets/{WorkspaceTree-Bo35HZpc.js → WorkspaceTree-yST2ByxM.js} +1 -1
  16. package/dist/web/assets/{file-links-DlYR_xxD.js → file-links-CtHFx6cd.js} +1 -1
  17. package/dist/web/assets/index-CWjsEUUy.js +10 -0
  18. package/dist/web/assets/task-links-ArhNpuGG.js +1 -0
  19. package/dist/web/downloads/teammy-inbox-skill.zip +0 -0
  20. package/dist/web/downloads/teammy-skill.zip +0 -0
  21. package/dist/web/index.html +2 -2
  22. package/package.json +1 -1
  23. package/dist/web/assets/Assistant-BLsq5HY7.js +0 -1
  24. package/dist/web/assets/Computers-B-8vIzy-.css +0 -1
  25. package/dist/web/assets/Computers-Dil0EHja.js +0 -12
  26. package/dist/web/assets/Dropdown-ClJ8qPeL.js +0 -55
  27. package/dist/web/assets/Files-CBGM_Ljm.js +0 -1
  28. package/dist/web/assets/ResourceLibrary-DPr1LKio.js +0 -6
  29. package/dist/web/assets/index-Dj9Jdm4p.js +0 -10
  30. package/dist/web/assets/task-links-zc4fWZyK.js +0 -1
package/dist/main.js CHANGED
@@ -491,6 +491,7 @@ var InteractionPartSchema = z5.object({
491
491
  });
492
492
  var InteractionDetailsSchema = z5.object({
493
493
  kind: z5.enum(["question", "approval", "plan"]).optional(),
494
+ delivery: z5.literal("async").optional(),
494
495
  autoApprove: z5.boolean().optional(),
495
496
  plan: z5.string().max(2e5).optional(),
496
497
  planSource: z5.object({ turnId: z5.string(), itemId: z5.string() }).optional(),
@@ -533,7 +534,7 @@ var SessionActivitySchema = z5.object({
533
534
  durationMs: z5.number().finite().nonnegative().optional(),
534
535
  // A native turn can end while the work is still waiting for a reply.
535
536
  // Null marks that distinction; older clients omit the result altogether.
536
- completedWork: z5.object({ preview: z5.string().max(previewLength * 2) }).nullable().optional()
537
+ completedWork: z5.object({ preview: z5.string().max(previewLength * 2), answer: z5.string().optional() }).nullable().optional()
537
538
  });
538
539
  var LocalSessionMessageSchema = z5.object({
539
540
  queue: z5.object({
@@ -564,9 +565,15 @@ var LocalSessionMessageSchema = z5.object({
564
565
  questions: z5.array(InteractionPartSchema)
565
566
  }).nullable()
566
567
  });
568
+ var sessionMessagePageSize = 60;
569
+ function questionNeedsAnswer(question) {
570
+ return question.state === "pending" && (!question.response || ["human_routed", "failed", "handled"].includes(question.submissionState ?? ""));
571
+ }
567
572
  var LocalSessionChatSchema = z5.object({
568
573
  canRewind: z5.boolean().default(false),
569
574
  cursor: z5.number().int(),
575
+ olderBefore: z5.number().int().positive().nullable().default(null),
576
+ pendingQuestions: z5.array(z5.object({ id: z5.string(), seq: z5.number().int() })).optional(),
570
577
  session: LocalSessionSchema,
571
578
  messages: z5.array(LocalSessionMessageSchema),
572
579
  commands: z5.array(SessionCommandSchema)
@@ -913,17 +920,20 @@ var ProjectSummarySchema = z9.object({
913
920
  description: z9.string()
914
921
  });
915
922
  var ProjectsSchema = z9.object({ projects: z9.array(ProjectSummarySchema) });
923
+ var MaxConcurrentRunsSchema = z9.number().int().positive().nullable();
916
924
  var SiteConfigSchema = z9.object({
917
925
  sync: SyncPolicySchema,
918
926
  publicServerUrl: ServerUrlSchema,
927
+ maxConcurrentRuns: MaxConcurrentRunsSchema.default(null),
919
928
  revision: RevisionSchema
920
929
  });
921
930
  var SiteConfigUpdateSchema = z9.object({
922
931
  publicServerUrl: ServerUrlSchema.optional(),
923
932
  sync: SyncPolicySchema.optional(),
933
+ maxConcurrentRuns: MaxConcurrentRunsSchema.optional(),
924
934
  expectedRevision: RevisionSchema
925
935
  }).strict().refine(
926
- (v) => v.publicServerUrl !== void 0 || v.sync !== void 0,
936
+ (v) => v.publicServerUrl !== void 0 || v.sync !== void 0 || v.maxConcurrentRuns !== void 0,
927
937
  "Provide a setting to update."
928
938
  );
929
939
  var UserSchema = z9.object({
@@ -947,6 +957,7 @@ var UserUpdateSchema = z9.object({
947
957
 
948
958
  // apps/server/site.ts
949
959
  import { randomBytes, createHash as createHash2 } from "node:crypto";
960
+ import { isDeepStrictEqual } from "node:util";
950
961
  var digest = (value) => createHash2("sha256").update(value).digest("hex");
951
962
  function requireSiteAdmin(identity) {
952
963
  if (identity.siteRole !== "admin")
@@ -975,7 +986,8 @@ var SiteRepository = class {
975
986
  JSON.stringify({
976
987
  publicServerUrl: value.publicServerUrl,
977
988
  revision: 1,
978
- sync: DEFAULT_POLICY
989
+ sync: DEFAULT_POLICY,
990
+ maxConcurrentRuns: null
979
991
  }),
980
992
  value.operationId,
981
993
  fingerprint3
@@ -1005,11 +1017,15 @@ var SiteRepository = class {
1005
1017
  const next = {
1006
1018
  ...current2,
1007
1019
  publicServerUrl: value.publicServerUrl ?? current2.publicServerUrl,
1008
- sync: value.sync ?? current2.sync
1020
+ sync: value.sync ?? current2.sync,
1021
+ maxConcurrentRuns: value.maxConcurrentRuns === void 0 ? current2.maxConcurrentRuns : value.maxConcurrentRuns
1009
1022
  };
1010
- if (JSON.stringify(next) === JSON.stringify(current2)) return current2;
1023
+ const clientPolicyChanged = next.publicServerUrl !== current2.publicServerUrl || !isDeepStrictEqual(next.sync, current2.sync);
1024
+ if (!clientPolicyChanged && next.maxConcurrentRuns === current2.maxConcurrentRuns)
1025
+ return current2;
1011
1026
  next.revision++;
1012
1027
  this.hub.db.prepare("UPDATE site_settings SET config_json=? WHERE id=1").run(JSON.stringify(next));
1028
+ if (!clientPolicyChanged) return next;
1013
1029
  for (const row of this.hub.db.prepare("SELECT id,config_json FROM projects").all()) {
1014
1030
  const config = ProjectConfigSchema.parse(JSON.parse(String(row.config_json)));
1015
1031
  config.publicServerUrl = next.publicServerUrl;
@@ -1106,7 +1122,7 @@ import { randomUUID as randomUUID26 } from "node:crypto";
1106
1122
  import { constants as constants3 } from "node:fs";
1107
1123
  import { lstat as lstat3, open as open5, readdir as readdir4 } from "node:fs/promises";
1108
1124
  import { isAbsolute, join as join14 } from "node:path";
1109
- import { setTimeout as delay } from "node:timers/promises";
1125
+ import { setTimeout as delay2 } from "node:timers/promises";
1110
1126
 
1111
1127
  // packages/protocol/workspace-import.ts
1112
1128
  import { z as z10 } from "zod";
@@ -1484,7 +1500,7 @@ var gitApiDefaults = {
1484
1500
  github: "https://api.github.com",
1485
1501
  gongfeng: "https://git.tencent.com/api/v3"
1486
1502
  };
1487
- var ProjectAgentConfigSchema = z13.object({
1503
+ var agentConfigFields = z13.object({
1488
1504
  provider: GitProviderSchema.default("github"),
1489
1505
  repositoryUrl: z13.string().trim().default(""),
1490
1506
  repository: z13.string().trim().default(""),
@@ -1497,7 +1513,8 @@ var ProjectAgentConfigSchema = z13.object({
1497
1513
  fetchIntervalSeconds: interval.default(300),
1498
1514
  idleSeconds: interval.default(1800),
1499
1515
  restartSeconds: interval.default(86400)
1500
- }).strict().refine((c) => c.compactAt < c.contextWindow, "\u538B\u7F29\u9608\u503C\u5E94\u5C0F\u4E8E\u6A21\u578B\u4E0A\u4E0B\u6587\u7A97\u53E3\u3002").transform(({ githubApiUrl, apiUrl, ...config }) => ({
1516
+ }).strict();
1517
+ var ProjectAgentConfigSchema = agentConfigFields.refine((c) => c.compactAt < c.contextWindow, "\u538B\u7F29\u9608\u503C\u5E94\u5C0F\u4E8E\u6A21\u578B\u4E0A\u4E0B\u6587\u7A97\u53E3\u3002").transform(({ githubApiUrl, apiUrl, ...config }) => ({
1501
1518
  ...config,
1502
1519
  apiUrl: (apiUrl ?? githubApiUrl ?? gitApiDefaults[config.provider]).replace(/\/+$/, "")
1503
1520
  }));
@@ -1508,6 +1525,10 @@ var ProjectAgentConfigUpdateSchema = z13.object({
1508
1525
  sshPrivateKey: z13.string().nullable().optional(),
1509
1526
  sshKnownHosts: z13.string().nullable().optional()
1510
1527
  }).strict();
1528
+ var ProjectAgentConfigPatchSchema = ProjectAgentConfigUpdateSchema.extend({
1529
+ config: z13.partialRecord(agentConfigFields.keyof().exclude(["githubApiUrl"]), z13.unknown()),
1530
+ refreshRepositoryImport: z13.boolean().optional()
1531
+ });
1511
1532
  var ProjectAgentSettingsSchema = z13.object({
1512
1533
  config: ProjectAgentConfigSchema,
1513
1534
  tokenConfigured: z13.boolean(),
@@ -2416,6 +2437,15 @@ var RoutingPolicySchema = z15.object({
2416
2437
  revision: z15.number().int().nonnegative()
2417
2438
  });
2418
2439
  var computerCompletionCategory = "computer.completed";
2440
+ var computerQuestionCategory = "computer.question";
2441
+ var computerReminderCategories = [
2442
+ computerCompletionCategory,
2443
+ computerQuestionCategory
2444
+ ];
2445
+ var isComputerReminder = (category) => category === computerCompletionCategory || category === computerQuestionCategory;
2446
+ var computerReminderPolicy = RoutingPolicySchema.pick({ wecom: true, revision: true }).extend({
2447
+ notify: z15.boolean().default(true)
2448
+ });
2419
2449
  var editablePolicy = RoutingPolicySchema.pick({
2420
2450
  category: true,
2421
2451
  notify: true,
@@ -2428,7 +2458,8 @@ var editablePolicy = RoutingPolicySchema.pick({
2428
2458
  var RoutingPolicyUpdateSchema = z15.discriminatedUnion("category", [
2429
2459
  editablePolicy,
2430
2460
  z15.object({
2431
- category: z15.literal(computerCompletionCategory),
2461
+ category: z15.enum(computerReminderCategories),
2462
+ notify: z15.boolean().default(true),
2432
2463
  wecom: z15.boolean(),
2433
2464
  expectedRevision: editablePolicy.shape.expectedRevision
2434
2465
  }).strict()
@@ -2445,7 +2476,8 @@ var RoutingModeUpdateSchema = RoutingModeSchema.omit({ revision: true }).extend(
2445
2476
  var RoutingSettingsSchema = z15.object({
2446
2477
  mode: RoutingModeSchema,
2447
2478
  policies: z15.array(RoutingPolicySchema),
2448
- computerCompletion: RoutingPolicySchema.pick({ wecom: true, revision: true }).optional(),
2479
+ computerCompletion: computerReminderPolicy.optional(),
2480
+ computerQuestion: computerReminderPolicy.optional(),
2449
2481
  managedAvailable: z15.boolean(),
2450
2482
  agentStatus: z15.enum(["closed", "unregistered", "disabled", "ready"]),
2451
2483
  wecomAvailable: z15.boolean(),
@@ -2515,9 +2547,9 @@ var EventRouting = class {
2515
2547
  savedPolicy(identity, category) {
2516
2548
  return this.hub.db.prepare("SELECT * FROM routing_policies WHERE project_id=? AND member_id=? AND category=?").get(identity.workspaceId, identity.memberId, category);
2517
2549
  }
2518
- computerCompletion(identity) {
2519
- const row = this.savedPolicy(identity, computerCompletionCategory);
2520
- return { wecom: !!row?.wecom, revision: Number(row?.revision ?? 0) };
2550
+ computerReminder(identity, category) {
2551
+ const row = this.savedPolicy(identity, category);
2552
+ return { notify: !!row?.notify, wecom: !!row?.wecom, revision: Number(row?.revision ?? 0) };
2521
2553
  }
2522
2554
  policy(identity, category) {
2523
2555
  const row = this.savedPolicy(identity, category);
@@ -2541,7 +2573,8 @@ var EventRouting = class {
2541
2573
  return {
2542
2574
  mode: this.mode(identity),
2543
2575
  policies: notificationCategories.map((category) => this.policy(identity, category)),
2544
- computerCompletion: this.computerCompletion(identity),
2576
+ computerCompletion: this.computerReminder(identity, computerCompletionCategory),
2577
+ computerQuestion: this.computerReminder(identity, computerQuestionCategory),
2545
2578
  managedAvailable: this.agentStatus(identity) === "ready",
2546
2579
  agentStatus: this.agentStatus(identity),
2547
2580
  wecomAvailable: !!this.hub.db.prepare(
@@ -2590,9 +2623,10 @@ var EventRouting = class {
2590
2623
  const saved = this.savedPolicy(identity, value.category);
2591
2624
  if (value.expectedRevision !== Number(saved?.revision ?? 0))
2592
2625
  throw new HubError(409, "ROUTING_POLICY_CHANGED", "\u8BBE\u7F6E\u5DF2\u53D8\u5316\uFF0C\u8BF7\u5237\u65B0\u540E\u91CD\u8BD5\u3002");
2593
- const reminder = value.category === computerCompletionCategory;
2594
- const notify = reminder || (value.notify ?? !!saved?.notify);
2595
- const autoHandle = !reminder && (value.autoHandle ?? (saved ? !!saved.auto_handle : defaultAutoHandle(value.category)));
2626
+ const reminder = isComputerReminder(value.category);
2627
+ const notify = value.notify ?? !!saved?.notify;
2628
+ const wecom = reminder ? notify && value.wecom : value.wecom ?? !!saved?.wecom;
2629
+ const autoHandle = !isComputerReminder(value.category) && (("autoHandle" in value ? value.autoHandle : void 0) ?? (saved ? !!saved.auto_handle : defaultAutoHandle(value.category)));
2596
2630
  this.hub.db.prepare(
2597
2631
  `INSERT INTO routing_policies(project_id,member_id,category,notify,wecom,revision,auto_handle) VALUES(?,?,?,?,?,?,?)
2598
2632
  ON CONFLICT(project_id,member_id,category) DO UPDATE SET notify=excluded.notify,wecom=excluded.wecom,revision=excluded.revision,auto_handle=excluded.auto_handle`
@@ -2601,14 +2635,14 @@ var EventRouting = class {
2601
2635
  identity.memberId,
2602
2636
  value.category,
2603
2637
  Number(notify),
2604
- Number(value.wecom ?? !!saved?.wecom),
2638
+ Number(wecom),
2605
2639
  value.expectedRevision + 1,
2606
2640
  Number(autoHandle)
2607
2641
  );
2608
- if (reminder && !value.wecom)
2642
+ if (reminder && !wecom)
2609
2643
  this.hub.db.prepare(
2610
2644
  "UPDATE wecom_deliveries SET state='cancelled' WHERE project_id=? AND user_id=? AND kind=? AND state='pending'"
2611
- ).run(identity.workspaceId, identity.memberId, computerCompletionCategory);
2645
+ ).run(identity.workspaceId, identity.memberId, value.category);
2612
2646
  return this.settings(identity);
2613
2647
  });
2614
2648
  }
@@ -6766,13 +6800,16 @@ function validateRewind(hub, identity, session, argument) {
6766
6800
  (row) => row.state !== "uncertain" || JSON.parse(String(row.argument)).messageId !== value.messageId
6767
6801
  ))
6768
6802
  throw new HubError(409, "REWIND_PENDING", "\u4E0A\u6B21\u56DE\u9000\u5C1A\u672A\u786E\u8BA4\uFF0C\u8BF7\u4ECE\u539F\u7F16\u8F91\u4F4D\u7F6E\u91CD\u8BD5\u3002");
6769
- const rows = hub.db.prepare(
6770
- "SELECT id,role FROM member_session_messages WHERE project_id=? AND member_id=? AND session_id=? AND superseded_by IS NULL ORDER BY seq"
6771
- ).all(identity.workspaceId, identity.memberId, session.id);
6772
- const target2 = rows.find((r) => r.id === value.messageId);
6803
+ const target2 = hub.db.prepare(
6804
+ "SELECT role FROM member_session_messages WHERE project_id=? AND member_id=? AND session_id=? AND id=? AND superseded_by IS NULL"
6805
+ ).get(identity.workspaceId, identity.memberId, session.id, value.messageId);
6773
6806
  if (!target2 || target2.role !== "user" || !value.messageId.startsWith("input:"))
6774
6807
  throw new HubError(400, "REWIND_TARGET", "\u8BF7\u9009\u62E9\u5F53\u524D\u4F1A\u8BDD\u4E2D\u7684\u7528\u6237\u6D88\u606F\u3002");
6775
- if (new MemberSessions(hub).chat(identity, session.id).messages.at(-1)?.id !== value.expectedLastMessage)
6808
+ const sessions2 = new MemberSessions(hub);
6809
+ let page = sessions2.chat(identity, session.id);
6810
+ while (!page.messages.length && page.olderBefore !== null)
6811
+ page = sessions2.chat(identity, session.id, { before: page.olderBefore });
6812
+ if (page.messages.at(-1)?.id !== value.expectedLastMessage)
6776
6813
  throw new HubError(409, "REWIND_CHANGED", "\u4F1A\u8BDD\u5DF2\u6709\u65B0\u6D88\u606F\uFF0C\u8BF7\u91CD\u65B0\u9009\u62E9\u7F16\u8F91\u4F4D\u7F6E\u3002");
6777
6814
  const input = new MemberExecution(hub).input(identity, value.messageId.slice(6));
6778
6815
  if (input.interaction || input.source.type !== "web_session")
@@ -6817,9 +6854,51 @@ function completeRewind(hub, identity, session, commandId, argument, result) {
6817
6854
  });
6818
6855
  }
6819
6856
 
6857
+ // apps/server/member-execution/transcript.ts
6858
+ function transcriptPage(hub, identity, session, window) {
6859
+ const scope2 = [identity.workspaceId, identity.memberId, session];
6860
+ const filter2 = "m.project_id=? AND m.member_id=? AND m.session_id=? AND m.superseded_by IS NULL";
6861
+ const select = `SELECT m.*,i.state input_state,i.id input_id,i.read_at input_read_at,i.payload_json,
6862
+ q.id question_id,q.code,q.state question_state,q.content_json FROM member_session_messages m
6863
+ LEFT JOIN member_agent_inputs i ON m.role='user' AND i.id=substr(m.id,7) AND m.id='input:'||i.id
6864
+ LEFT JOIN member_agent_questions q ON q.id=m.id WHERE ${filter2}`;
6865
+ const range = (from) => {
6866
+ const rows2 = hub.db.prepare(select + " AND m.seq>=? ORDER BY m.seq").all(...scope2, from);
6867
+ const older = hub.db.prepare(`SELECT 1 FROM member_session_messages m WHERE ${filter2} AND m.seq<? LIMIT 1`).get(...scope2, from);
6868
+ return { rows: rows2, olderBefore: older ? from : null };
6869
+ };
6870
+ if (window.from !== void 0) return range(window.from);
6871
+ const rows = hub.db.prepare(select + " AND m.seq<? ORDER BY m.seq DESC LIMIT ?").all(...scope2, window.before ?? Number.MAX_SAFE_INTEGER, sessionMessagePageSize + 1);
6872
+ const hasOlder = rows.length > sessionMessagePageSize;
6873
+ if (hasOlder) rows.pop();
6874
+ rows.reverse();
6875
+ const olderBefore = hasOlder ? Number(rows[0].seq) : null;
6876
+ if (window.question && olderBefore !== null) {
6877
+ const target2 = hub.db.prepare(
6878
+ `SELECT m.seq FROM member_session_messages m JOIN member_agent_questions q ON q.id=m.id WHERE ${filter2} AND m.id=?`
6879
+ ).get(...scope2, window.question);
6880
+ if (target2 && Number(target2.seq) < olderBefore) return range(Number(target2.seq));
6881
+ }
6882
+ return { rows, olderBefore };
6883
+ }
6884
+
6820
6885
  // apps/server/member-execution/sessions.ts
6821
6886
  import { randomUUID as randomUUID13 } from "node:crypto";
6822
6887
  import { z as z25 } from "zod";
6888
+ var unreadTurn = `EXISTS(SELECT 1 FROM member_session_messages m
6889
+ WHERE m.project_id=s.project_id AND m.session_id=s.id AND m.seq>s.read_seq
6890
+ AND m.superseded_by IS NULL AND m.role='assistant' AND m.state IN('sent','succeeded','failed','interrupted','uncertain')
6891
+ AND (json_extract(m.activity_json,'$.kind')='turn' OR (m.activity_json IS NULL AND m.source='agent-final')))`;
6892
+ var unseenQuestion = `EXISTS(SELECT 1 FROM member_agent_questions q
6893
+ JOIN member_session_messages m ON m.id=q.id
6894
+ WHERE q.project_id=s.project_id AND q.member_id=s.member_id AND q.state='pending'
6895
+ AND m.session_id=s.id AND m.superseded_by IS NULL
6896
+ AND NOT EXISTS(SELECT 1 FROM member_session_question_views v WHERE v.question_id=q.id))`;
6897
+ function questionDelivery(question, session) {
6898
+ if (question.delivery) return question.delivery;
6899
+ if (session.provider === "codex" && !question.kind && question.approval === false && question.questions.every((p, i) => p.id === String(i + 1) && p.freeText && !p.descriptions))
6900
+ return "async";
6901
+ }
6823
6902
  var MemberSessions = class {
6824
6903
  constructor(hub) {
6825
6904
  this.hub = hub;
@@ -6957,13 +7036,10 @@ var MemberSessions = class {
6957
7036
  const row = this.hub.db.prepare(
6958
7037
  `SELECT s.*,
6959
7038
  EXISTS(SELECT 1 FROM member_agent_bindings b WHERE b.project_id=s.project_id AND b.session_id=s.id) bound,
6960
- EXISTS(SELECT 1 FROM member_session_messages m
6961
- WHERE m.project_id=s.project_id AND m.session_id=s.id AND m.seq>s.read_seq
6962
- AND m.superseded_by IS NULL AND m.role='assistant' AND m.state IN('sent','succeeded','failed','interrupted','uncertain')
6963
- AND (json_extract(m.activity_json,'$.kind')='turn'
6964
- OR (m.activity_json IS NULL AND m.source='agent-final'))) unread
7039
+ (${unreadTurn} OR (EXISTS(SELECT 1 FROM routing_policies p WHERE p.project_id=s.project_id
7040
+ AND p.member_id=s.member_id AND p.category=? AND p.notify=1) AND ${unseenQuestion})) unread
6965
7041
  FROM member_agent_sessions s WHERE s.project_id=? AND s.member_id=? AND s.id=?`
6966
- ).get(identity.workspaceId, identity.memberId, id);
7042
+ ).get(computerQuestionCategory, identity.workspaceId, identity.memberId, id);
6967
7043
  if (row && deviceScope(identity)) this.directory(identity, String(row.directory_id));
6968
7044
  if (!row) throw new HubError(404, "SESSION_NOT_FOUND", "\u627E\u4E0D\u5230\u672C\u4EBA\u7684\u4F1A\u8BDD\u3002");
6969
7045
  return LocalSessionSchema.parse({
@@ -7011,6 +7087,16 @@ var MemberSessions = class {
7011
7087
  (a, b) => Date.parse(b.updatedAt) - Date.parse(a.updatedAt) || a.id.localeCompare(b.id)
7012
7088
  );
7013
7089
  }
7090
+ unreadReminders(identity, completion, question) {
7091
+ if (!completion && !question) return 0;
7092
+ return Number(
7093
+ this.hub.db.prepare(
7094
+ `SELECT COUNT(*) n FROM member_agent_sessions s
7095
+ WHERE s.project_id=? AND s.member_id=? AND s.hidden=0
7096
+ AND ((? AND ${unreadTurn}) OR (? AND ${unseenQuestion}))`
7097
+ ).get(identity.workspaceId, identity.memberId, Number(completion), Number(question)).n
7098
+ );
7099
+ }
7014
7100
  forContext(identity, context) {
7015
7101
  const row = this.hub.db.prepare(
7016
7102
  "SELECT target_json,directory_id FROM member_agent_reply_contexts WHERE id=? AND project_id=? AND member_id=?"
@@ -7254,20 +7340,48 @@ var MemberSessions = class {
7254
7340
  this.hub.db.prepare("UPDATE member_agent_sessions SET activity_at=? WHERE project_id=? AND id=?").run((/* @__PURE__ */ new Date()).toISOString(), identity.workspaceId, session);
7255
7341
  return !!written.changes;
7256
7342
  }
7257
- chat(identity, id) {
7343
+ eventCursor(identity, id) {
7344
+ const row = this.hub.db.prepare(
7345
+ `SELECT (SELECT COALESCE(MAX(seq),0) FROM member_session_events WHERE project_id=s.project_id AND session_id=s.id) seq
7346
+ FROM member_agent_sessions s WHERE s.project_id=? AND s.member_id=? AND s.id=?`
7347
+ ).get(identity.workspaceId, identity.memberId, id);
7348
+ if (!row) throw new HubError(404, "SESSION_NOT_FOUND", "\u627E\u4E0D\u5230\u672C\u4EBA\u7684\u4F1A\u8BDD\u3002");
7349
+ return Number(row.seq);
7350
+ }
7351
+ chat(identity, id, window = {}) {
7352
+ const cursor = this.eventCursor(identity, id);
7258
7353
  const session = this.get(identity, id);
7259
- const rows = this.hub.db.prepare(
7260
- `SELECT m.*,i.state input_state,i.id input_id,i.read_at input_read_at,i.payload_json,q.id question_id,q.code,q.state question_state,q.content_json FROM member_session_messages m
7261
- LEFT JOIN member_agent_inputs i ON 'input:'||i.id=m.id LEFT JOIN member_agent_questions q ON q.id=m.id
7262
- WHERE m.project_id=? AND m.member_id=? AND m.session_id=? AND m.superseded_by IS NULL ORDER BY m.seq`
7263
- ).all(identity.workspaceId, identity.memberId, id);
7354
+ const { rows, olderBefore } = transcriptPage(this.hub, identity, id, window);
7264
7355
  const replies = /* @__PURE__ */ new Map();
7265
- const questions = new Map(
7266
- rows.filter((row) => row.question_id).map((row) => [row.question_id, row])
7356
+ const inputs = new Map(
7357
+ rows.filter((r) => r.input_id).map((r) => [String(r.input_id), JSON.parse(String(r.payload_json))])
7267
7358
  );
7359
+ const questionIds = rows.flatMap((r) => r.question_id ? [String(r.question_id)] : []);
7360
+ for (const input of inputs.values())
7361
+ if (input.interaction?.action === "answer") questionIds.push(input.interaction.question);
7362
+ const questionRows = this.hub.db.prepare(
7363
+ `SELECT q.id question_id,q.content_json,q.state,m.seq
7364
+ FROM member_agent_questions q JOIN member_session_messages m ON m.id=q.id
7365
+ WHERE q.project_id=? AND q.member_id=? AND m.session_id=? AND m.superseded_by IS NULL AND
7366
+ (q.state='pending' OR q.id IN (SELECT value FROM json_each(?))
7367
+ OR json_extract(q.content_json,'$.response.inputId') IN (SELECT value FROM json_each(?))) ORDER BY m.seq`
7368
+ ).all(
7369
+ identity.workspaceId,
7370
+ identity.memberId,
7371
+ id,
7372
+ JSON.stringify(questionIds),
7373
+ JSON.stringify([...inputs.keys()])
7374
+ );
7375
+ const questions = new Map(questionRows.map((row) => [row.question_id, row]));
7268
7376
  const folded = /* @__PURE__ */ new Set();
7269
- for (const row of rows) {
7270
- if (!row.payload_json) continue;
7377
+ const answerRows = questions.size ? this.hub.db.prepare(
7378
+ `SELECT i.id input_id,i.state input_state,i.payload_json
7379
+ FROM member_agent_inputs i JOIN member_session_messages m ON m.id='input:'||i.id
7380
+ WHERE i.project_id=? AND i.member_id=? AND json_extract(i.payload_json,'$.interaction.action')='answer'
7381
+ AND json_extract(i.payload_json,'$.interaction.question') IN (SELECT value FROM json_each(?))
7382
+ AND m.session_id=? AND m.superseded_by IS NULL ORDER BY m.seq`
7383
+ ).all(identity.workspaceId, identity.memberId, JSON.stringify([...questions.keys()]), id) : [];
7384
+ for (const row of answerRows) {
7271
7385
  const input = JSON.parse(String(row.payload_json));
7272
7386
  if (input.source.type !== "web_session" || input.interaction?.action !== "answer") continue;
7273
7387
  const question = questions.get(input.interaction.question);
@@ -7295,9 +7409,18 @@ var MemberSessions = class {
7295
7409
  });
7296
7410
  folded.add(String(row.input_id));
7297
7411
  }
7298
- for (const row of rows) {
7299
- const response = row.content_json && JSON.parse(String(row.content_json)).response;
7412
+ const pendingQuestions = [];
7413
+ for (const row of questionRows) {
7414
+ const content = JSON.parse(String(row.content_json));
7415
+ const response = content.response;
7300
7416
  if (response?.inputId) folded.add(response.inputId);
7417
+ const reply = replies.get(String(row.question_id));
7418
+ if (questionDelivery(content, session) === "async" && questionNeedsAnswer({
7419
+ state: String(row.state),
7420
+ response: response ?? reply?.response,
7421
+ submissionState: reply?.state
7422
+ }))
7423
+ pendingQuestions.push({ id: String(row.question_id), seq: Number(row.seq) });
7301
7424
  }
7302
7425
  const runtime = new MemberExecution(this.hub).runtime(identity, session.directory);
7303
7426
  const runtimeConfig = JSON.parse(String(runtime?.config_json ?? "{}"));
@@ -7308,8 +7431,8 @@ var MemberSessions = class {
7308
7431
  );
7309
7432
  const queueInfo = (row) => {
7310
7433
  if (!row.input_id || !row.payload_json) return {};
7311
- const input = JSON.parse(String(row.payload_json));
7312
- if (!input.delivery || input.source.type !== "web_session" || input.interaction) return {};
7434
+ const input = inputs.get(String(row.input_id));
7435
+ if (!input?.delivery || input.source.type !== "web_session" || input.interaction) return {};
7313
7436
  const queued = input.delivery === "queue";
7314
7437
  const edit = queued ? this.hub.db.prepare("SELECT revision,cancelled FROM member_session_input_edits WHERE input_id=?").get(String(row.input_id)) : void 0;
7315
7438
  const state = edit?.cancelled ? "cancelled" : progress.get(String(row.input_id))?.state ?? (row.input_read_at ? "handled" : row.input_state === "accepted" ? "queued" : String(row.input_state));
@@ -7325,42 +7448,44 @@ var MemberSessions = class {
7325
7448
  }
7326
7449
  };
7327
7450
  };
7328
- const messages = rows.filter((row) => !row.input_id || !folded.has(String(row.input_id))).map((row) => ({
7329
- ...queueInfo(row),
7330
- id: String(row.id),
7331
- seq: Number(row.seq),
7332
- role: String(row.role),
7333
- body: String(row.body),
7334
- ...row.payload_json && JSON.parse(String(row.payload_json)).attachments ? { attachments: JSON.parse(String(row.payload_json)).attachments } : {},
7335
- ...row.payload_json && JSON.parse(String(row.payload_json)).images ? { images: JSON.parse(String(row.payload_json)).images } : {},
7336
- source: String(row.source),
7337
- state: String(row.input_state ?? row.state),
7338
- createdAt: String(row.created_at),
7339
- activity: row.activity_json ? JSON.parse(String(row.activity_json)) : null,
7340
- question: row.question_id ? {
7341
- id: String(row.question_id),
7342
- code: String(row.code),
7343
- state: String(row.question_state),
7344
- approval: !!JSON.parse(String(row.content_json)).approval,
7345
- questions: JSON.parse(String(row.content_json)).questions,
7346
- kind: JSON.parse(String(row.content_json)).kind,
7347
- autoApprove: JSON.parse(String(row.content_json)).autoApprove,
7348
- autoApproveAt: runtime && Number(runtime.lease_until) > Date.now() && row.question_state === "pending" && !replies.has(String(row.question_id)) ? runtimeConfig.sessions?.find((s) => s.id === id)?.approvals?.find((q) => q.id === row.question_id)?.autoApproveAt ?? null : null,
7349
- plan: JSON.parse(String(row.content_json)).plan,
7350
- planSource: JSON.parse(String(row.content_json)).planSource,
7351
- actions: JSON.parse(String(row.content_json)).actions,
7352
- response: JSON.parse(String(row.content_json)).response ? QuestionResponseSchema.parse(JSON.parse(String(row.content_json)).response) : replies.get(String(row.question_id))?.response ?? null,
7353
- submissionState: replies.get(String(row.question_id))?.state ?? null
7354
- } : null
7355
- }));
7356
- const cursor = Number(
7357
- this.hub.db.prepare(
7358
- "SELECT COALESCE(MAX(seq),0) seq FROM member_session_events WHERE project_id=? AND session_id=?"
7359
- ).get(identity.workspaceId, id).seq
7360
- );
7451
+ const messages = rows.filter((row) => !row.input_id || !folded.has(String(row.input_id))).map((row) => {
7452
+ const input = inputs.get(String(row.input_id));
7453
+ const content = row.question_id ? JSON.parse(String(row.content_json)) : null;
7454
+ return {
7455
+ ...queueInfo(row),
7456
+ id: String(row.id),
7457
+ seq: Number(row.seq),
7458
+ role: String(row.role),
7459
+ body: String(row.body),
7460
+ ...input?.attachments ? { attachments: input.attachments } : {},
7461
+ ...input?.images ? { images: input.images } : {},
7462
+ source: String(row.source),
7463
+ state: String(row.input_state ?? row.state),
7464
+ createdAt: String(row.created_at),
7465
+ activity: row.activity_json ? JSON.parse(String(row.activity_json)) : null,
7466
+ question: content ? {
7467
+ id: String(row.question_id),
7468
+ code: String(row.code),
7469
+ state: String(row.question_state),
7470
+ approval: !!content.approval,
7471
+ questions: content.questions,
7472
+ kind: content.kind,
7473
+ delivery: questionDelivery(content, session),
7474
+ autoApprove: content.autoApprove,
7475
+ autoApproveAt: runtime && Number(runtime.lease_until) > Date.now() && row.question_state === "pending" && !replies.has(String(row.question_id)) ? runtimeConfig.sessions?.find((s) => s.id === id)?.approvals?.find((q) => q.id === row.question_id)?.autoApproveAt ?? null : null,
7476
+ plan: content.plan,
7477
+ planSource: content.planSource,
7478
+ actions: content.actions,
7479
+ response: content.response ? QuestionResponseSchema.parse(content.response) : replies.get(String(row.question_id))?.response ?? null,
7480
+ submissionState: replies.get(String(row.question_id))?.state ?? null
7481
+ } : null
7482
+ };
7483
+ });
7361
7484
  return {
7362
7485
  session,
7363
7486
  messages,
7487
+ olderBefore,
7488
+ pendingQuestions,
7364
7489
  commands: this.commands(identity, id),
7365
7490
  cursor,
7366
7491
  canRewind: rewindAvailable(this.hub, identity, session)
@@ -7469,7 +7594,8 @@ var MemberSessions = class {
7469
7594
  commands(identity, session) {
7470
7595
  requireProjectActor(this.hub, identity);
7471
7596
  return this.hub.db.prepare(
7472
- `SELECT c.* FROM member_session_commands c JOIN member_agent_sessions s ON s.project_id=c.project_id AND s.id=c.session_id
7597
+ `SELECT c.id,c.session_id,c.kind,c.argument,c.input_id,c.state,c.error
7598
+ FROM member_session_commands c JOIN member_agent_sessions s ON s.project_id=c.project_id AND s.id=c.session_id
7473
7599
  JOIN member_agent_directories d ON d.project_id=s.project_id AND d.id=s.directory_id
7474
7600
  WHERE c.project_id=? AND c.member_id=? AND (? IS NULL OR c.session_id=?) AND (? IS NULL OR d.device_id=?) ORDER BY c.rowid`
7475
7601
  ).all(
@@ -7552,6 +7678,16 @@ var MemberSessions = class {
7552
7678
  if (!["queued", "running"].includes(String(row.state)) || row.instance && row.instance !== value.instance && value.state !== "uncertain")
7553
7679
  throw new HubError(409, "COMMAND_OWNED", "\u64CD\u4F5C\u7ED3\u679C\u9700\u8981\u6838\u5BF9\uFF0C\u4E0D\u80FD\u91CD\u590D\u6267\u884C\u3002");
7554
7680
  this.hub.db.prepare("UPDATE member_session_commands SET state=?,instance=?,error=? WHERE id=?").run(value.state, value.instance, value.error, id);
7681
+ if (row.kind === "stop" && (value.state === "running" || value.state === "succeeded")) {
7682
+ const report = JSON.parse(String(runtime.config_json));
7683
+ const input2 = runningSessionInput(report.sessions?.find((s) => s.id === row.session_id));
7684
+ if (value.state === "running" && input2)
7685
+ this.hub.db.prepare("UPDATE member_session_commands SET result_json=? WHERE id=?").run(JSON.stringify(input2), id);
7686
+ if (value.state === "succeeded" && (!row.result_json || !input2 || row.result_json === JSON.stringify(input2)))
7687
+ this.hub.db.prepare(
7688
+ "UPDATE member_agent_sessions SET state='idle' WHERE project_id=? AND id=? AND state IN ('working','waiting')"
7689
+ ).run(identity.workspaceId, row.session_id);
7690
+ }
7555
7691
  if (value.state === "succeeded") {
7556
7692
  if (row.kind === "rewind") {
7557
7693
  completeRewind(
@@ -8068,7 +8204,11 @@ function registerSessionAttachments(server, hub, previews) {
8068
8204
  reply.raw
8069
8205
  );
8070
8206
  if (!content)
8071
- throw new HubError(404, "DIRECTORY_FILE_UNAVAILABLE", "\u6587\u4EF6\u4E0D\u5B58\u5728\u3001\u4E0D\u53EF\u8BFB\u6216\u5DF2\u79FB\u51FA\u5F53\u524D\u76EE\u5F55\u3002");
8207
+ throw new HubError(
8208
+ 404,
8209
+ "DIRECTORY_FILE_UNAVAILABLE",
8210
+ "\u6587\u4EF6\u4E0D\u5B58\u5728\u3001\u4E0D\u53EF\u8BFB\u6216\u4E0D\u5728\u6B64\u8BBE\u5907\u7684\u9884\u89C8\u8303\u56F4\u5185\u3002"
8211
+ );
8072
8212
  if (view === "html")
8073
8213
  return htmlPreviewResponse(reply).header("Content-Length", content.size).send(content.stream);
8074
8214
  return reply.type("application/octet-stream").header("Cache-Control", "private, no-store").header("X-Content-Type-Options", "nosniff").header("Content-Disposition", attachmentDisposition(basename(path))).header("X-Teammy-File-Size", content.total).header("Content-Length", content.size).send(content.stream);
@@ -8141,6 +8281,10 @@ function associateTaskFolders(hub, project, input) {
8141
8281
 
8142
8282
  // apps/server/member-execution/store.ts
8143
8283
  import { randomUUID as randomUUID15 } from "node:crypto";
8284
+ function runningSessionInput(report) {
8285
+ if (report?.state !== "working" && report?.state !== "waiting") return;
8286
+ return report.inputs?.filter((i) => i.state === "running" || i.state === "dispatching").at(-1)?.id;
8287
+ }
8144
8288
  var MemberExecution = class {
8145
8289
  constructor(hub, now6 = Date.now) {
8146
8290
  this.hub = hub;
@@ -8244,6 +8388,7 @@ var MemberExecution = class {
8244
8388
  this.now() + 45e3,
8245
8389
  JSON.stringify(value)
8246
8390
  );
8391
+ let previousSessions;
8247
8392
  for (const item of value.sessions ?? []) {
8248
8393
  const session = new MemberSessions(this.hub).get(identity, item.id);
8249
8394
  const dir = new MemberSessions(this.hub).directory(identity, session.directory);
@@ -8261,10 +8406,17 @@ var MemberExecution = class {
8261
8406
  state: "succeeded"
8262
8407
  });
8263
8408
  }
8409
+ let state = item.state;
8410
+ const input2 = runningSessionInput(item);
8411
+ if (session.state === "idle" && input2 && current2?.instance === value.instance) {
8412
+ previousSessions ??= JSON.parse(String(current2.config_json)).sessions ?? [];
8413
+ if (runningSessionInput(previousSessions.find((s) => s.id === item.id)) === input2)
8414
+ state = "idle";
8415
+ }
8264
8416
  this.hub.db.prepare(
8265
8417
  "UPDATE member_agent_sessions SET state=?,applied_revision=?,effective_json=?,cwd=?,error=?,native_session=COALESCE(?,native_session) WHERE project_id=? AND id=?"
8266
8418
  ).run(
8267
- item.state,
8419
+ state,
8268
8420
  item.appliedRevision,
8269
8421
  item.effectiveConfig ? JSON.stringify(item.effectiveConfig) : null,
8270
8422
  item.cwd,
@@ -8862,9 +9014,9 @@ function flushEventRouting(hub) {
8862
9014
  const routing = new EventRouting(hub);
8863
9015
  diagnosticTransaction(hub, () => {
8864
9016
  for (const row of hub.db.prepare(
8865
- `SELECT w.* FROM wecom_deliveries w WHERE w.project_id IS NOT NULL AND w.kind NOT IN ('outbox',?)
9017
+ `SELECT w.* FROM wecom_deliveries w WHERE w.project_id IS NOT NULL AND w.kind NOT IN ('outbox',?,?)
8866
9018
  AND NOT EXISTS(SELECT 1 FROM routing_deliveries d WHERE d.channel='wecom_delivery' AND d.target=w.id) ORDER BY w.rowid LIMIT 100`
8867
- ).all(computerCompletionCategory)) {
9019
+ ).all(...computerReminderCategories)) {
8868
9020
  const context = row.channel_json ? JSON.parse(String(row.channel_json)) : {};
8869
9021
  const request = routing.fixed(
8870
9022
  {
@@ -8970,7 +9122,11 @@ function replyToRoutedRequest(hub, identity, input) {
8970
9122
  return diagnosticTransaction(hub, () => {
8971
9123
  const source = new MemberExecution(hub).input(identity, value.inputId);
8972
9124
  if (source.source.type !== "routed.event" || source.state !== "accepted")
8973
- throw new HubError(403, "ROUTED_REQUEST_REQUIRED", "\u53EA\u80FD\u56DE\u5E94\u672C\u5730\u5DF2\u63A5\u624B\u7684\u539F\u8BF7\u6C42\u3002");
9125
+ throw new HubError(
9126
+ 403,
9127
+ "ROUTED_REQUEST_REQUIRED",
9128
+ "\u5F53\u524D\u6CA1\u6709\u53EF\u7528\u6B64\u5DE5\u5177\u56DE\u5E94\u7684\u5DF2\u63A5\u624B\u4E8B\u4EF6\u3002\u666E\u901A\u4F1A\u8BDD\u8BF7\u76F4\u63A5\u7ED9\u51FA\u6700\u7EC8\u7B54\u590D\u3002"
9129
+ );
8974
9130
  const row = hub.db.prepare("SELECT * FROM routing_requests WHERE id=? AND member_id=? AND input_id=?").get(source.source.ref, identity.memberId, source.id);
8975
9131
  if (!row || row.handler !== "managed" || row.requires_human)
8976
9132
  throw new HubError(403, "ROUTED_REQUEST_OWNER", "\u8BE5\u8BF7\u6C42\u4E0D\u7531\u5F53\u524D Agent \u56DE\u5E94\u3002");
@@ -9174,7 +9330,29 @@ var WecomStore = class {
9174
9330
  );
9175
9331
  }
9176
9332
  queueComputerCompletion(identity, session, turn, input) {
9177
- if (!new EventRouting(this.hub).computerCompletion(identity).wecom) return;
9333
+ this.queueComputerReminder(
9334
+ identity,
9335
+ session,
9336
+ computerCompletionCategory,
9337
+ JSON.stringify([identity.workspaceId, session.id, turn.turnId]),
9338
+ () => {
9339
+ if (turn.completedWork === null) return null;
9340
+ if (turn.completedWork === void 0 && this.legacyTurnWaiting(identity, input))
9341
+ return null;
9342
+ const answer = turn.completedWork?.answer ?? this.turnAnswer(identity, session, turn.turnId) ?? turn.completedWork?.preview;
9343
+ return "\u672C\u8F6E\u5DE5\u4F5C\u5DF2\u5B8C\u6210\u3002" + (answer ? "\n" + answer : "");
9344
+ }
9345
+ );
9346
+ }
9347
+ queueComputerQuestion(identity, session, question) {
9348
+ this.queueComputerReminder(identity, session, computerQuestionCategory, question.id, () => {
9349
+ const label = question.kind === "plan" ? "\u8BA1\u5212\u7B49\u5F85\u786E\u8BA4" : question.approval ? "\u6743\u9650\u7533\u8BF7\u7B49\u5F85\u5BA1\u6279" : "\u6709\u95EE\u9898\u7B49\u5F85\u56DE\u7B54";
9350
+ const preview = turnAnswerPreview(question.questions[0].text);
9351
+ return label + "\u3002" + (preview ? "\n" + wecomLinkLabel(preview) : "");
9352
+ });
9353
+ }
9354
+ queueComputerReminder(identity, session, category, source, summary) {
9355
+ if (!new EventRouting(this.hub).computerReminder(identity, category).wecom) return;
9178
9356
  const config = new WecomConfig(this.hub).row();
9179
9357
  if (!config?.enabled) return;
9180
9358
  const bot = String(config.bot_id);
@@ -9184,39 +9362,41 @@ var WecomStore = class {
9184
9362
  identity.memberId
9185
9363
  );
9186
9364
  if (!external) return;
9187
- const preview = turn.completedWork === void 0 ? this.legacyTurnPreview(identity, session, turn.turnId, input) : turn.completedWork?.preview;
9188
- if (preview == null) return;
9365
+ const body = summary();
9366
+ if (body === null) return;
9189
9367
  const directory = new MemberSessions(this.hub).directory(identity, session.directory);
9190
9368
  const query2 = new URLSearchParams({ directory: session.directory, session: session.id });
9369
+ if (category === computerQuestionCategory) query2.set("question", source);
9370
+ const base = new SiteRepository(this.hub).config().publicServerUrl;
9191
9371
  const link4 = wecomLinks(
9192
- `[\u67E5\u770B\u4F1A\u8BDD](/projects/${encodeURIComponent(identity.workspaceId)}/computers?${query2})`,
9193
- new SiteRepository(this.hub).config().publicServerUrl
9194
- );
9195
- this.queue(
9196
- bot,
9197
- external,
9198
- computerCompletionCategory,
9199
- JSON.stringify([identity.workspaceId, session.id, turn.turnId]),
9200
- `${wecomLinkLabel(String(directory.name))} \xB7 ${wecomLinkLabel(session.title)}\uFF5C\u672C\u8F6E\u5DE5\u4F5C\u5DF2\u5B8C\u6210\u3002
9201
- ${preview ? wecomLinkLabel(preview) + "\n" : ""}${link4}`,
9202
- identity
9372
+ `[${category === computerQuestionCategory ? "\u67E5\u770B\u5E76\u5904\u7406" : "\u67E5\u770B\u4F1A\u8BDD"}](/projects/${encodeURIComponent(identity.workspaceId)}/computers?${query2})`,
9373
+ base
9203
9374
  );
9204
- }
9205
- legacyTurnPreview(identity, session, turn, input) {
9206
- const waiting = this.hub.db.prepare(
9375
+ const content = `${wecomLinkLabel(String(directory.name))} \xB7 ${wecomLinkLabel(session.title)}\uFF5C${wecomLinks(body, base)}`;
9376
+ const footer = "\n" + link4;
9377
+ const parts = wecomParts(content, 20480 - Buffer.byteLength(footer));
9378
+ parts[parts.length - 1] += footer;
9379
+ for (const [index, part] of parts.entries())
9380
+ this.queue(bot, external, category, index ? `${source}:${index}` : source, part, identity);
9381
+ }
9382
+ legacyTurnWaiting(identity, input) {
9383
+ return this.hub.db.prepare(
9207
9384
  `SELECT 1 FROM member_agent_question_codes c LEFT JOIN member_agent_questions q ON q.id=c.id
9208
9385
  WHERE c.project_id=? AND c.member_id=? AND c.reply_context=? AND
9209
9386
  ((q.id IS NULL AND c.reserved_after_input >= (SELECT seq FROM member_agent_inputs WHERE id=?)) OR
9210
9387
  (q.state='pending' AND EXISTS (SELECT 1 FROM member_agent_message_inputs i WHERE i.operation_id=q.id AND i.input_id=?)))
9211
9388
  LIMIT 1`
9212
9389
  ).get(identity.workspaceId, identity.memberId, input.replyContext, input.id, input.id);
9213
- if (waiting) return null;
9390
+ }
9391
+ turnAnswer(identity, session, turn) {
9214
9392
  const answer = this.hub.db.prepare(
9215
- `SELECT body FROM member_session_messages WHERE project_id=? AND session_id=? AND superseded_by IS NULL
9216
- AND role='assistant' AND state IN ('succeeded','sent') AND json_extract(activity_json,'$.kind')='answer'
9217
- AND json_extract(activity_json,'$.turnId')=? ORDER BY seq DESC LIMIT 1`
9393
+ `SELECT COALESCE(final.body,m.body) body FROM member_session_messages m
9394
+ LEFT JOIN member_agent_messages final ON final.operation_id=m.id
9395
+ WHERE m.project_id=? AND m.session_id=? AND m.superseded_by IS NULL
9396
+ AND m.role='assistant' AND m.state IN ('succeeded','sent') AND json_extract(m.activity_json,'$.kind')='answer'
9397
+ AND json_extract(m.activity_json,'$.turnId')=? ORDER BY m.seq DESC LIMIT 1`
9218
9398
  ).get(identity.workspaceId, session.id, turn);
9219
- return turnAnswerPreview(String(answer?.body ?? ""));
9399
+ return answer ? String(answer.body) : void 0;
9220
9400
  }
9221
9401
  subscribe(bot, external, code) {
9222
9402
  const row = this.hub.db.prepare("SELECT * FROM wecom_codes WHERE code_hash=? AND bot_id=? AND expires_at>?").get(hash2(code.toUpperCase()), bot, Date.now());
@@ -9278,7 +9458,7 @@ ${preview ? wecomLinkLabel(preview) + "\n" : ""}${link4}`,
9278
9458
  }
9279
9459
  const binding = new WecomIdentities(this.hub).binding(bot, msg.from.userid);
9280
9460
  if (!binding) {
9281
- notice("\u8BF7\u5148\u767B\u5F55 Teammy\uFF0C\u5728\u9879\u76EE\u8BBE\u7F6E \u2192 \u4F01\u4E1A\u5FAE\u4FE1\u4E2D\u83B7\u53D6\u7ED1\u5B9A\u7801\uFF0C\u53D1\u9001 /bind <\u7ED1\u5B9A\u7801>\u3002");
9461
+ notice("\u8BF7\u5148\u767B\u5F55 Teammy\uFF0C\u5728\u9879\u76EE\u8BBE\u7F6E \u2192 \u6D88\u606F\u4E0E\u901A\u77E5\u4E2D\u83B7\u53D6\u7ED1\u5B9A\u7801\uFF0C\u53D1\u9001 /bind <\u7ED1\u5B9A\u7801>\u3002");
9282
9462
  return;
9283
9463
  }
9284
9464
  const user = String(binding.user_id);
@@ -9509,11 +9689,22 @@ ${text2}` : text2;
9509
9689
  } catch {
9510
9690
  return false;
9511
9691
  }
9512
- if (delivery.kind === computerCompletionCategory)
9513
- return new EventRouting(this.hub).computerCompletion({
9514
- memberId: delivery.user_id,
9515
- workspaceId: delivery.project_id
9516
- }).wecom;
9692
+ if (isComputerReminder(delivery.kind)) {
9693
+ if (!new EventRouting(this.hub).computerReminder(
9694
+ {
9695
+ memberId: delivery.user_id,
9696
+ workspaceId: delivery.project_id
9697
+ },
9698
+ delivery.kind
9699
+ ).wecom)
9700
+ return false;
9701
+ return delivery.kind === computerCompletionCategory || !!this.hub.db.prepare(
9702
+ `SELECT 1 FROM member_agent_questions q JOIN member_session_messages m ON m.id=q.id
9703
+ JOIN member_agent_sessions s ON s.project_id=m.project_id AND s.id=m.session_id
9704
+ WHERE q.id=? AND q.project_id=? AND q.member_id=? AND q.state='pending'
9705
+ AND m.superseded_by IS NULL AND s.hidden=0`
9706
+ ).get(delivery.source_id, delivery.project_id, delivery.user_id);
9707
+ }
9517
9708
  if (delivery.kind === "outbox")
9518
9709
  return new EventRouting(this.hub).wecomAllowed(
9519
9710
  delivery.project_id,
@@ -9578,13 +9769,14 @@ var ExecutionBridge = class {
9578
9769
  AND json_extract(activity_json,'$.turnId')=? LIMIT 1`
9579
9770
  ).get(identity.workspaceId, session.id, turn.turnId);
9580
9771
  if (previous && previous.id !== value.operationId) return { ok: true };
9772
+ const activity = turn?.completedWork?.answer !== void 0 ? { ...turn, completedWork: { preview: turn.completedWork.preview } } : value.activity;
9581
9773
  const written = sessions2.message(identity, session.id, {
9582
9774
  id: value.operationId,
9583
9775
  role: "assistant",
9584
9776
  body: value.body,
9585
9777
  source: "agent",
9586
9778
  state: value.state,
9587
- ...value.activity ? { activity: value.activity } : {}
9779
+ ...activity ? { activity } : {}
9588
9780
  });
9589
9781
  if (written && turn && !previous && turn.completedWork !== null)
9590
9782
  new WecomStore(this.hub).queueComputerCompletion(identity, session, turn, source);
@@ -9930,6 +10122,8 @@ var ExecutionBridge = class {
9930
10122
  state: "sent",
9931
10123
  ...value.activity ? { activity: value.activity } : {}
9932
10124
  });
10125
+ if (session && value.question && (target2.kind !== "private" || target2.recipient !== identity.memberId))
10126
+ new WecomStore(this.hub).queueComputerQuestion(identity, session, value.question);
9933
10127
  for (const inputId of inputIds)
9934
10128
  this.hub.db.prepare("INSERT INTO member_agent_message_inputs VALUES(?,?)").run(value.operationId, inputId);
9935
10129
  if (value.final && !value.question && target2.kind === "group") {
@@ -10174,12 +10368,13 @@ CREATE TABLE wecom_groups(bot_id TEXT NOT NULL,chat_id TEXT NOT NULL,project_id
10174
10368
  CREATE TABLE wecom_group_requests(run_id TEXT PRIMARY KEY,bot_id TEXT NOT NULL,chat_id TEXT NOT NULL,project_id TEXT NOT NULL,user_id TEXT NOT NULL,collected INTEGER NOT NULL DEFAULT 0);
10175
10369
  `;
10176
10370
  var digest5 = (code) => createHash15("sha256").update(code.toUpperCase()).digest("hex");
10177
- function wecomParts(text2) {
10371
+ function wecomParts(text2, maxBytes = 17e3) {
10372
+ if (Buffer.byteLength(text2) <= maxBytes) return text2 ? [text2] : [];
10178
10373
  const parts = [];
10179
10374
  let part = "", bytes3 = 0;
10180
10375
  for (const char of text2) {
10181
10376
  const size2 = Buffer.byteLength(char);
10182
- if (bytes3 + size2 > 17e3) {
10377
+ if (bytes3 + size2 > maxBytes) {
10183
10378
  parts.push(part);
10184
10379
  part = "";
10185
10380
  bytes3 = 0;
@@ -10320,7 +10515,7 @@ var WecomGroups = class {
10320
10515
  }
10321
10516
  const group = this.hub.db.prepare("SELECT * FROM wecom_groups WHERE bot_id=? AND chat_id=?").get(bot, chat);
10322
10517
  if (!group) {
10323
- notice("\u8BF7\u5148\u5728 Teammy \u9879\u76EE\u8BBE\u7F6E \u2192 \u4F01\u4E1A\u5FAE\u4FE1\u83B7\u53D6\u7FA4\u7ED1\u5B9A\u7801\uFF0C\u5728\u672C\u7FA4\u53D1\u9001 /bind <\u7ED1\u5B9A\u7801>\u3002");
10518
+ notice("\u8BF7\u5148\u5728 Teammy \u9879\u76EE\u8BBE\u7F6E \u2192 \u9879\u76EE\u7FA4\u4E0E\u9891\u9053\u83B7\u53D6\u7FA4\u7ED1\u5B9A\u7801\uFF0C\u5728\u672C\u7FA4\u53D1\u9001 /bind <\u7ED1\u5B9A\u7801>\u3002");
10324
10519
  return;
10325
10520
  }
10326
10521
  const identity = {
@@ -11101,6 +11296,77 @@ function aiRetryDelay(retryIndex, random = Math.random) {
11101
11296
  return index === retryDelays.length - 1 ? retryDelays[index] : Math.round(retryDelays[index] * (0.8 + random() * 0.4));
11102
11297
  }
11103
11298
 
11299
+ // apps/server/ai/dispatch.ts
11300
+ import { setTimeout as delay } from "node:timers/promises";
11301
+ function hasAiRunCapacity(db, at) {
11302
+ const limit = db.prepare(
11303
+ "SELECT json_extract(config_json,'$.maxConcurrentRuns') AS max_runs FROM site_settings WHERE id=1"
11304
+ ).get()?.max_runs;
11305
+ if (limit == null) return true;
11306
+ const row = db.prepare(
11307
+ `
11308
+ SELECT (SELECT count(*) FROM ai_jobs WHERE status='running' AND lease_until>?) +
11309
+ (SELECT count(*) FROM session_analysis_jobs WHERE status='running' AND lease_until>?) +
11310
+ (SELECT count(*) FROM project_agent_runs WHERE state='running' AND lease_until>?) AS running
11311
+ `
11312
+ ).get(at, at, at);
11313
+ return Number(row.running) < Number(limit);
11314
+ }
11315
+ async function dispatchAiJobs(options) {
11316
+ const pending = /* @__PURE__ */ new Set();
11317
+ const errors = /* @__PURE__ */ new Map();
11318
+ let nextSchedule = 0;
11319
+ const report = (phase, error) => {
11320
+ const code = error instanceof HubError ? error.code : "AI_DISPATCH_FAILED";
11321
+ if (errors.get(phase) !== code)
11322
+ process.stderr.write(
11323
+ JSON.stringify({ component: options.component, phase, error: code }) + "\n"
11324
+ );
11325
+ errors.set(phase, code);
11326
+ try {
11327
+ options.onError?.(phase, error);
11328
+ } catch {
11329
+ process.stderr.write("LOG_STORE_UNAVAILABLE: dispatch diagnostic could not be saved.\n");
11330
+ }
11331
+ if (options.once) throw error;
11332
+ };
11333
+ try {
11334
+ do {
11335
+ if (options.stop.aborted) break;
11336
+ if (Date.now() >= nextSchedule) {
11337
+ nextSchedule = Date.now() + 15e3;
11338
+ try {
11339
+ await options.schedule();
11340
+ errors.delete("schedule");
11341
+ options.onRecovered?.("schedule");
11342
+ } catch (error) {
11343
+ report("schedule", error);
11344
+ }
11345
+ }
11346
+ let job;
11347
+ try {
11348
+ job = options.claim();
11349
+ errors.delete("claim");
11350
+ options.onRecovered?.("claim");
11351
+ } catch (error) {
11352
+ report("claim", error);
11353
+ }
11354
+ if (job !== void 0) {
11355
+ const running = options.execute(job).then(() => options.onRecovered?.("execute")).catch((error) => report("execute", error)).finally(() => pending.delete(running));
11356
+ pending.add(running);
11357
+ if (options.once) await running;
11358
+ else await delay(0, void 0, { signal: options.stop }).catch(() => {
11359
+ });
11360
+ } else if (!options.once) {
11361
+ await delay(1e3, void 0, { signal: options.stop }).catch(() => {
11362
+ });
11363
+ }
11364
+ } while (!options.once);
11365
+ } finally {
11366
+ await Promise.allSettled(pending);
11367
+ }
11368
+ }
11369
+
11104
11370
  // apps/server/agents/store.ts
11105
11371
  var now4 = () => (/* @__PURE__ */ new Date()).toISOString();
11106
11372
  var AgentStore = class {
@@ -11341,7 +11607,7 @@ var AgentStore = class {
11341
11607
  AND NOT EXISTS(SELECT 1 FROM project_agent_runs active WHERE active.conversation_id=r.conversation_id AND active.state='running')
11342
11608
  ORDER BY r.rowid LIMIT 1`
11343
11609
  ).get(project, at);
11344
- if (!run) return void 0;
11610
+ if (!run || !hasAiRunCapacity(db, at)) return void 0;
11345
11611
  const text2 = batchInput(this.hub, project, run);
11346
11612
  const token = randomUUID22();
11347
11613
  db.prepare(
@@ -12495,7 +12761,7 @@ async function runWorkspaceImports(hub, signal, once = false) {
12495
12761
  }
12496
12762
  }
12497
12763
  if (once) break;
12498
- await delay(1e3, void 0, { signal }).catch(() => {
12764
+ await delay2(1e3, void 0, { signal }).catch(() => {
12499
12765
  });
12500
12766
  } while (!signal.aborted);
12501
12767
  } finally {
@@ -13688,6 +13954,10 @@ ALTER TABLE member_agent_sessions ADD COLUMN hidden INTEGER NOT NULL DEFAULT 0;
13688
13954
  var sessionRewindMigration = `
13689
13955
  ALTER TABLE member_session_messages ADD COLUMN superseded_by TEXT;
13690
13956
  `;
13957
+ var sessionTranscriptIndexMigration = `
13958
+ CREATE INDEX IF NOT EXISTS member_input_question_answer ON member_agent_inputs(project_id,member_id,json_extract(payload_json,'$.interaction.question'))
13959
+ WHERE json_extract(payload_json,'$.interaction.action')='answer';
13960
+ `;
13691
13961
 
13692
13962
  // apps/server/session-library.ts
13693
13963
  var columns = "id,workspace_id,owner,session_key,agent,native_id,cwd,title,revision,updated_at,message_count,hash,size";
@@ -14095,6 +14365,14 @@ var controlMigration = String.raw`
14095
14365
  var deviceMigration = String.raw`
14096
14366
  CREATE TABLE device_enrollments(workspace_id TEXT NOT NULL, member_id TEXT NOT NULL, operation_id TEXT NOT NULL, fingerprint TEXT NOT NULL, PRIMARY KEY(workspace_id,member_id,operation_id));
14097
14367
  `;
14368
+ var clientUpdateMigration = `
14369
+ CREATE TABLE IF NOT EXISTS client_update_devices(
14370
+ workspace_id TEXT NOT NULL, member_id TEXT NOT NULL, device_id TEXT NOT NULL, installation TEXT NOT NULL, status_json TEXT NOT NULL,
14371
+ PRIMARY KEY(workspace_id,member_id,device_id),
14372
+ FOREIGN KEY(workspace_id,member_id,device_id) REFERENCES member_devices(workspace_id,member_id,device_id) ON DELETE CASCADE);
14373
+ CREATE TABLE IF NOT EXISTS client_update_preferences(member_id TEXT NOT NULL,installation TEXT NOT NULL,enabled INTEGER NOT NULL,
14374
+ PRIMARY KEY(member_id,installation));
14375
+ `;
14098
14376
  var multiDeviceMigration = `
14099
14377
  CREATE TABLE member_devices (
14100
14378
  workspace_id TEXT NOT NULL, member_id TEXT NOT NULL, device_id TEXT NOT NULL,
@@ -15378,63 +15656,6 @@ async function compactSessionHandoff(options) {
15378
15656
  return { result, usage };
15379
15657
  }
15380
15658
 
15381
- // apps/server/ai/dispatch.ts
15382
- import { setTimeout as delay2 } from "node:timers/promises";
15383
- async function dispatchAiJobs(options) {
15384
- const pending = /* @__PURE__ */ new Set();
15385
- const errors = /* @__PURE__ */ new Map();
15386
- let nextSchedule = 0;
15387
- const report = (phase, error) => {
15388
- const code = error instanceof HubError ? error.code : "AI_DISPATCH_FAILED";
15389
- if (errors.get(phase) !== code)
15390
- process.stderr.write(
15391
- JSON.stringify({ component: options.component, phase, error: code }) + "\n"
15392
- );
15393
- errors.set(phase, code);
15394
- try {
15395
- options.onError?.(phase, error);
15396
- } catch {
15397
- process.stderr.write("LOG_STORE_UNAVAILABLE: dispatch diagnostic could not be saved.\n");
15398
- }
15399
- if (options.once) throw error;
15400
- };
15401
- try {
15402
- do {
15403
- if (options.stop.aborted) break;
15404
- if (Date.now() >= nextSchedule) {
15405
- nextSchedule = Date.now() + 15e3;
15406
- try {
15407
- await options.schedule();
15408
- errors.delete("schedule");
15409
- options.onRecovered?.("schedule");
15410
- } catch (error) {
15411
- report("schedule", error);
15412
- }
15413
- }
15414
- let job;
15415
- try {
15416
- job = options.claim();
15417
- errors.delete("claim");
15418
- options.onRecovered?.("claim");
15419
- } catch (error) {
15420
- report("claim", error);
15421
- }
15422
- if (job !== void 0) {
15423
- const running = options.execute(job).then(() => options.onRecovered?.("execute")).catch((error) => report("execute", error)).finally(() => pending.delete(running));
15424
- pending.add(running);
15425
- if (options.once) await running;
15426
- else await delay2(0, void 0, { signal: options.stop }).catch(() => {
15427
- });
15428
- } else if (!options.once) {
15429
- await delay2(1e3, void 0, { signal: options.stop }).catch(() => {
15430
- });
15431
- }
15432
- } while (!options.once);
15433
- } finally {
15434
- await Promise.allSettled(pending);
15435
- }
15436
- }
15437
-
15438
15659
  // apps/server/ai/session-analysis.ts
15439
15660
  var jobAddress = (job) => ({
15440
15661
  workspace: job.workspace_id,
@@ -15564,7 +15785,7 @@ function claimSessionAnalysis(hub, at) {
15564
15785
  return transaction(hub.db, () => {
15565
15786
  hub.db.prepare(
15566
15787
  `UPDATE session_analysis_jobs SET status='queued',attempts=MAX(0,attempts-1),
15567
- run_token=NULL,lease_until=NULL,error='AI_WORKER_INTERRUPTED',due_at=? WHERE status='running' AND lease_until<?`
15788
+ run_token=NULL,lease_until=NULL,error='AI_WORKER_INTERRUPTED',due_at=? WHERE status='running' AND lease_until<=?`
15568
15789
  ).run(at, at);
15569
15790
  const rows = hub.db.prepare(
15570
15791
  `SELECT * FROM session_analysis_jobs WHERE status='queued' AND due_at<=?
@@ -15594,6 +15815,7 @@ function claimSessionAnalysis(hub, at) {
15594
15815
  });
15595
15816
  continue;
15596
15817
  }
15818
+ if (!hasAiRunCapacity(hub.db, at)) return void 0;
15597
15819
  let runtime = selected.runtime_json ? SessionRuntimeSchema2.parse(JSON.parse(selected.runtime_json)) : loadSessionRuntime(selected.kind);
15598
15820
  if (selected.kind === "handoff" && runtime.config.version < 4)
15599
15821
  runtime = loadSessionRuntime("handoff");
@@ -15636,9 +15858,10 @@ async function runSessionAnalysisCycle(hub, stop, at = Date.now(), claimed) {
15636
15858
  const timer = setInterval(() => {
15637
15859
  try {
15638
15860
  requireAnalysisAccess(hub, { workspaceId: s.workspace, memberId: s.owner });
15861
+ const now6 = Date.now();
15639
15862
  if (!hub.db.prepare(
15640
- `UPDATE session_analysis_jobs SET lease_until=? WHERE id=? AND run_token=? AND status='running'`
15641
- ).run(Date.now() + 3e4, job.id, job.run_token).changes)
15863
+ `UPDATE session_analysis_jobs SET lease_until=? WHERE id=? AND run_token=? AND status='running' AND lease_until>?`
15864
+ ).run(now6 + 3e4, job.id, job.run_token, now6).changes)
15642
15865
  lost.abort();
15643
15866
  } catch {
15644
15867
  lost.abort();
@@ -18641,7 +18864,9 @@ var migrations = [
18641
18864
  multiDeviceMigration,
18642
18865
  batchInputReceiptsMigration,
18643
18866
  computerCompletionMigration,
18644
- taskCardNumbersMigration
18867
+ taskCardNumbersMigration,
18868
+ sessionTranscriptIndexMigration,
18869
+ clientUpdateMigration
18645
18870
  ];
18646
18871
  var HubStore = class {
18647
18872
  constructor(directory) {
@@ -19705,7 +19930,7 @@ var AiJobs = class {
19705
19930
  const row = this.hub.db.prepare(
19706
19931
  "SELECT * FROM ai_jobs WHERE status='queued' AND (next_retry_at IS NULL OR next_retry_at<=?) ORDER BY created_at,id LIMIT 1"
19707
19932
  ).get(at);
19708
- if (!row) return void 0;
19933
+ if (!row || !hasAiRunCapacity(this.hub.db, at)) return void 0;
19709
19934
  const token = randomUUID34(), attempt = Number(row.attempt_count) + 1, date = now5();
19710
19935
  this.hub.db.prepare(
19711
19936
  "UPDATE ai_jobs SET status='running',attempt_count=?,run_token=?,lease_until=?,updated_at=?,error=NULL,next_retry_at=NULL WHERE id=?"
@@ -23792,6 +24017,19 @@ import { ZodError } from "zod";
23792
24017
 
23793
24018
  // packages/protocol/devices.ts
23794
24019
  import { z as z75 } from "zod";
24020
+
24021
+ // packages/protocol/release-version.ts
24022
+ var stableVersion = /^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)$/;
24023
+ function compareVersions(left, right) {
24024
+ const a = left.split(".").map(BigInt), b = right.split(".").map(BigInt);
24025
+ for (let i = 0; i < 3; i++) {
24026
+ if (a[i] < b[i]) return -1;
24027
+ if (a[i] > b[i]) return 1;
24028
+ }
24029
+ return 0;
24030
+ }
24031
+
24032
+ // packages/protocol/devices.ts
23795
24033
  var CredentialSchema = z75.string().regex(/^tmy_[a-f0-9]{64}$/);
23796
24034
  var EnrollmentSchema = z75.object({
23797
24035
  operationId: z75.uuid(),
@@ -23823,6 +24061,17 @@ var DeviceStatusSchema = z75.object({
23823
24061
  reportError: z75.string().max(2e3).nullable(),
23824
24062
  lastSync: SyncSummarySchema.nullable()
23825
24063
  }).strict();
24064
+ var release = z75.string().max(64).regex(stableVersion);
24065
+ var ClientUpdateStatusSchema = z75.object({
24066
+ running: z75.string().min(1).max(64),
24067
+ waiting: release.optional(),
24068
+ issue: z75.string().max(1500).optional()
24069
+ });
24070
+ var ClientUpdateReportSchema = ClientUpdateStatusSchema.extend({ installation: z75.uuid() });
24071
+ var ClientUpdatePolicySchema = z75.object({
24072
+ enabled: z75.boolean(),
24073
+ target: release.nullable()
24074
+ });
23826
24075
  var WebDevicesSchema = z75.object({
23827
24076
  devices: z75.array(
23828
24077
  z75.object({
@@ -23831,13 +24080,46 @@ var WebDevicesSchema = z75.object({
23831
24080
  name: z75.string().nullish(),
23832
24081
  bound: z75.boolean(),
23833
24082
  lastSeenAt: z75.string().nullable(),
23834
- status: DeviceStatusSchema.nullable()
24083
+ status: DeviceStatusSchema.nullable(),
24084
+ autoUpdate: ClientUpdateStatusSchema.extend({ enabled: z75.boolean() }).optional()
23835
24085
  })
23836
24086
  )
23837
24087
  });
23838
24088
 
23839
24089
  // apps/server/control-routes.ts
23840
- function registerControlRoutes(server, store) {
24090
+ import { z as z76 } from "zod";
24091
+ function registerControlRoutes(server, store, target2) {
24092
+ server.put("/devices/self/client-update", async (request) => {
24093
+ const { workspaceId, memberId, deviceId } = authorizeDevice(store, request);
24094
+ const { installation, ...status } = ClientUpdateReportSchema.parse(request.body);
24095
+ store.db.prepare(
24096
+ `INSERT INTO client_update_devices VALUES(?,?,?,?,?) ON CONFLICT(workspace_id,member_id,device_id)
24097
+ DO UPDATE SET installation=excluded.installation,status_json=excluded.status_json
24098
+ WHERE installation<>excluded.installation OR status_json<>excluded.status_json`
24099
+ ).run(workspaceId, memberId, deviceId, installation, JSON.stringify(status));
24100
+ const preference = store.db.prepare(
24101
+ "SELECT enabled FROM client_update_preferences WHERE member_id=? AND installation=?"
24102
+ );
24103
+ const isEnabled = () => preference.get(memberId, installation)?.enabled !== 0;
24104
+ if (!isEnabled()) return { enabled: false, target: null };
24105
+ const release2 = await target2(status.running);
24106
+ const enabled = isEnabled();
24107
+ return { enabled, target: enabled ? release2 : null };
24108
+ });
24109
+ server.put("/web/devices/:device/client-update", async (request) => {
24110
+ webMutation(request);
24111
+ const { workspaceId, memberId } = authorizeWeb(store, request);
24112
+ const { device } = z76.object({ device: z76.uuid() }).parse(request.params);
24113
+ const { enabled } = z76.object({ enabled: z76.boolean() }).parse(request.body);
24114
+ const result = store.db.prepare(
24115
+ `INSERT INTO client_update_preferences(member_id,installation,enabled)
24116
+ SELECT member_id,installation,? FROM client_update_devices WHERE workspace_id=? AND member_id=? AND device_id=?
24117
+ ON CONFLICT(member_id,installation) DO UPDATE SET enabled=excluded.enabled`
24118
+ ).run(Number(enabled), workspaceId, memberId, device);
24119
+ if (!result.changes)
24120
+ throw new HubError(404, "DEVICE_NOT_FOUND", "\u627E\u4E0D\u5230\u652F\u6301\u81EA\u52A8\u66F4\u65B0\u7684\u672C\u673A\u8FDE\u63A5\u3002");
24121
+ return { ok: true };
24122
+ });
23841
24123
  server.put("/devices/self/status", async (request) => {
23842
24124
  const identity = authorizeDevice(store, request);
23843
24125
  new ProjectRepository(store).config(identity);
@@ -23856,16 +24138,25 @@ function registerControlRoutes(server, store) {
23856
24138
  server.get("/web/devices", async (request) => {
23857
24139
  const identity = authorizeWeb(store, request);
23858
24140
  const devices = store.db.prepare(
23859
- `SELECT m.member_id,b.device_id,COALESCE(json_extract(r.config_json,'$.computer.name'),NULLIF(b.label,''),b.device_id) name,d.seen_at,d.status_json
24141
+ `SELECT m.member_id,b.device_id,COALESCE(json_extract(r.config_json,'$.computer.name'),NULLIF(b.label,''),b.device_id) name,d.seen_at,d.status_json,
24142
+ u.status_json update_status,p.enabled update_enabled
23860
24143
  FROM members m LEFT JOIN member_devices b USING(workspace_id,member_id)
23861
24144
  LEFT JOIN device_status d ON d.workspace_id=b.workspace_id AND d.member_id=b.member_id AND d.device_id=b.device_id
23862
24145
  LEFT JOIN member_agent_runtimes r ON r.project_id=m.workspace_id AND r.member_id=m.member_id AND r.device_id=b.device_id
24146
+ LEFT JOIN client_update_devices u ON u.workspace_id=b.workspace_id AND u.member_id=b.member_id AND u.device_id=b.device_id AND u.member_id=?
24147
+ LEFT JOIN client_update_preferences p ON p.member_id=u.member_id AND p.installation=u.installation
23863
24148
  WHERE m.workspace_id=? ORDER BY m.member_id,name,b.device_id`
23864
- ).all(identity.workspaceId).map((row) => ({
24149
+ ).all(identity.memberId, identity.workspaceId).map((row) => ({
23865
24150
  memberId: String(row.member_id),
23866
24151
  deviceId: row.device_id,
23867
24152
  name: row.name,
23868
24153
  bound: Boolean(row.device_id),
24154
+ ...row.update_status ? {
24155
+ autoUpdate: {
24156
+ ...JSON.parse(String(row.update_status)),
24157
+ enabled: row.update_enabled !== 0
24158
+ }
24159
+ } : {},
23869
24160
  lastSeenAt: row.seen_at === null ? null : String(row.seen_at),
23870
24161
  status: row.status_json ? DeviceStatusSchema.parse(JSON.parse(String(row.status_json))) : null
23871
24162
  }));
@@ -23874,7 +24165,7 @@ function registerControlRoutes(server, store) {
23874
24165
  }
23875
24166
 
23876
24167
  // apps/server/project-routes.ts
23877
- import { z as z76 } from "zod";
24168
+ import { z as z77 } from "zod";
23878
24169
 
23879
24170
  // apps/server/project-activity.ts
23880
24171
  function projectWork(hub, identity) {
@@ -24144,7 +24435,7 @@ function registerProjectScopeRoutes(server, store) {
24144
24435
  );
24145
24436
  server.post("/project/onboarding", async (request) => {
24146
24437
  webMutation(request);
24147
- z76.object({}).strict().parse(request.body ?? {});
24438
+ z77.object({}).strict().parse(request.body ?? {});
24148
24439
  return recordProjectOnboarding(store, authorizeWeb(store, request));
24149
24440
  });
24150
24441
  server.get(
@@ -24206,7 +24497,7 @@ function registerProjectScopeRoutes(server, store) {
24206
24497
  });
24207
24498
  server.patch("/web/members/:id", async (request) => {
24208
24499
  webMutation(request);
24209
- const { id } = z76.object({ id: NameSchema }).parse(request.params);
24500
+ const { id } = z77.object({ id: NameSchema }).parse(request.params);
24210
24501
  return project.updateMember(
24211
24502
  authorizeWeb(store, request),
24212
24503
  id,
@@ -24215,23 +24506,23 @@ function registerProjectScopeRoutes(server, store) {
24215
24506
  });
24216
24507
  server.post("/web/members/:id/device-reset", async (request) => {
24217
24508
  webMutation(request);
24218
- const { id } = z76.object({ id: NameSchema }).parse(request.params);
24219
- const { expectedRevision, deviceId } = z76.object({
24220
- expectedRevision: z76.number().int().nonnegative().optional(),
24221
- deviceId: z76.uuid().optional()
24509
+ const { id } = z77.object({ id: NameSchema }).parse(request.params);
24510
+ const { expectedRevision, deviceId } = z77.object({
24511
+ expectedRevision: z77.number().int().nonnegative().optional(),
24512
+ deviceId: z77.uuid().optional()
24222
24513
  }).strict().parse(request.body ?? {});
24223
24514
  return project.resetDevice(authorizeWeb(store, request), id, expectedRevision, deviceId);
24224
24515
  });
24225
24516
  }
24226
24517
 
24227
24518
  // apps/server/diagnostics/routes.ts
24228
- import { z as z77 } from "zod";
24519
+ import { z as z78 } from "zod";
24229
24520
  function registerDiagnosticRoutes(server, hub) {
24230
24521
  for (const kind2 of ["file", "related"])
24231
24522
  server.get(`/diagnostics/:id/${kind2}`, async (req, reply) => {
24232
24523
  const identity = authorizeWeb(hub, req);
24233
24524
  requireSiteAdmin(identity);
24234
- const { id } = z77.object({ id: z77.uuid() }).parse(req.params);
24525
+ const { id } = z78.object({ id: z78.uuid() }).parse(req.params);
24235
24526
  const logs = new Diagnostics(hub);
24236
24527
  const row = logs.get(identity.workspaceId, id);
24237
24528
  reply.header("x-content-type-options", "nosniff");
@@ -24245,7 +24536,7 @@ function registerDiagnosticRoutes(server, hub) {
24245
24536
  }
24246
24537
 
24247
24538
  // apps/server/site-routes.ts
24248
- import { z as z78 } from "zod";
24539
+ import { z as z79 } from "zod";
24249
24540
 
24250
24541
  // apps/server/devices.ts
24251
24542
  var DeviceRepository = class {
@@ -24374,7 +24665,7 @@ function registerSiteRoutes(server, store) {
24374
24665
  "/api/v1/web/session",
24375
24666
  { onRequest: async (request) => webMutation(request) },
24376
24667
  async (request, reply) => {
24377
- const { id } = z78.object({ id: NameSchema }).strict().parse(request.body);
24668
+ const { id } = z79.object({ id: NameSchema }).strict().parse(request.body);
24378
24669
  if (server.teammyTaiAuth) {
24379
24670
  if (id !== server.teammyTaiAuth.identity(request).loginName)
24380
24671
  throw new HubError(403, "TAI_IDENTITY_MISMATCH", "\u767B\u5F55 ID \u5FC5\u987B\u4E0E\u5F53\u524D\u516C\u53F8\u8D26\u53F7\u4E00\u81F4\u3002");
@@ -24387,7 +24678,7 @@ function registerSiteRoutes(server, store) {
24387
24678
  server.patch("/api/v1/web/session", async (request) => {
24388
24679
  webMutation(request);
24389
24680
  const identity = site.identity(cookieToken(request));
24390
- const { displayName } = z78.object({ displayName: z78.string().trim().max(120) }).strict().parse(request.body);
24681
+ const { displayName } = z79.object({ displayName: z79.string().trim().max(120) }).strict().parse(request.body);
24391
24682
  return site.renameSelf(identity, displayName);
24392
24683
  });
24393
24684
  server.delete("/api/v1/web/session", async (request, reply) => {
@@ -24438,7 +24729,7 @@ function registerSiteRoutes(server, store) {
24438
24729
  }
24439
24730
 
24440
24731
  // apps/server/session-routes.ts
24441
- import { z as z79 } from "zod";
24732
+ import { z as z80 } from "zod";
24442
24733
  function registerSessionRoutes(server, store) {
24443
24734
  const sessions2 = new SessionRepository(store);
24444
24735
  server.get(
@@ -24448,7 +24739,7 @@ function registerSessionRoutes(server, store) {
24448
24739
  server.put("/web/session-library", async (request) => {
24449
24740
  webMutation(request);
24450
24741
  const identity = authorizeWeb(store, request);
24451
- const { enabled } = z79.object({ enabled: z79.boolean() }).strict().parse(request.body);
24742
+ const { enabled } = z80.object({ enabled: z80.boolean() }).strict().parse(request.body);
24452
24743
  return setSessionLibraryPreference(store, identity, enabled);
24453
24744
  });
24454
24745
  const device = (request) => typeof request.headers["x-teammy-device"] === "string" ? request.headers["x-teammy-device"] : void 0;
@@ -24458,9 +24749,9 @@ function registerSessionRoutes(server, store) {
24458
24749
  authorize(request);
24459
24750
  }
24460
24751
  };
24461
- const pagination = z79.object({
24462
- after: z79.coerce.number().pipe(RevisionSchema).default(0),
24463
- limit: z79.coerce.number().int().min(1).max(100).default(50)
24752
+ const pagination = z80.object({
24753
+ after: z80.coerce.number().pipe(RevisionSchema).default(0),
24754
+ limit: z80.coerce.number().int().min(1).max(100).default(50)
24464
24755
  });
24465
24756
  server.post(
24466
24757
  "/sessions/commits",
@@ -24474,17 +24765,17 @@ function registerSessionRoutes(server, store) {
24474
24765
  server.get("/sessions", async (request) => {
24475
24766
  const q = pagination.extend({
24476
24767
  owner: NameSchema.optional(),
24477
- order: z79.enum(["created", "title", "updated"]).default("created")
24768
+ order: z80.enum(["created", "title", "updated"]).default("created")
24478
24769
  }).parse(request.query);
24479
24770
  return sessions2.list(authorizeRead(store, request), q.after, q.limit, q.owner, q.order);
24480
24771
  });
24481
24772
  server.get("/sessions/stats", async (request) => sessions2.stats(authorizeRead(store, request)));
24482
24773
  server.get("/sessions/search", async (request) => {
24483
24774
  const q = pagination.extend({
24484
- order: z79.enum(["created", "updated"]).default("created"),
24775
+ order: z80.enum(["created", "updated"]).default("created"),
24485
24776
  owner: NameSchema.optional(),
24486
24777
  sessionKey: HashSchema.optional(),
24487
- q: z79.string().min(1).max(500).refine((s) => !s.includes("\0"))
24778
+ q: z80.string().min(1).max(500).refine((s) => !s.includes("\0"))
24488
24779
  }).parse(request.query);
24489
24780
  return sessions2.search(
24490
24781
  authorizeRead(store, request),
@@ -24496,17 +24787,17 @@ function registerSessionRoutes(server, store) {
24496
24787
  );
24497
24788
  });
24498
24789
  server.get("/sessions/:owner/:key", async (request) => {
24499
- const p = z79.object({ owner: NameSchema, key: HashSchema }).parse(request.params);
24500
- const q = z79.object({ revision: z79.coerce.number().pipe(RevisionSchema).optional() }).parse(request.query);
24790
+ const p = z80.object({ owner: NameSchema, key: HashSchema }).parse(request.params);
24791
+ const q = z80.object({ revision: z80.coerce.number().pipe(RevisionSchema).optional() }).parse(request.query);
24501
24792
  return sessions2.read(authorizeRead(store, request), p.owner, p.key, q.revision);
24502
24793
  });
24503
24794
  server.get("/sessions/:owner/:key/baseline", guard, async (request) => {
24504
- const p = z79.object({ owner: NameSchema, key: HashSchema }).parse(request.params);
24795
+ const p = z80.object({ owner: NameSchema, key: HashSchema }).parse(request.params);
24505
24796
  return sessions2.baseline(authorize(request), p.owner, p.key);
24506
24797
  });
24507
24798
  server.get("/sessions/:owner/:key/analysis/:kind", async (request) => {
24508
- const p = z79.object({ owner: NameSchema, key: HashSchema, kind: SessionAnalysisKindSchema }).parse(request.params);
24509
- const q = z79.object({ revision: z79.coerce.number().pipe(RevisionSchema).optional() }).parse(request.query);
24799
+ const p = z80.object({ owner: NameSchema, key: HashSchema, kind: SessionAnalysisKindSchema }).parse(request.params);
24800
+ const q = z80.object({ revision: z80.coerce.number().pipe(RevisionSchema).optional() }).parse(request.query);
24510
24801
  const identity = authorizeRead(store, request);
24511
24802
  return sessionAnalysisState(
24512
24803
  store,
@@ -24518,13 +24809,13 @@ function registerSessionRoutes(server, store) {
24518
24809
  });
24519
24810
  server.post("/sessions/:owner/:key/handoff", async (request) => {
24520
24811
  if (!request.headers.authorization) webMutation(request);
24521
- const p = z79.object({ owner: NameSchema, key: HashSchema }).parse(request.params);
24812
+ const p = z80.object({ owner: NameSchema, key: HashSchema }).parse(request.params);
24522
24813
  return requestSessionHandoff(store, authorizeRead(store, request), p.owner, p.key);
24523
24814
  });
24524
24815
  }
24525
24816
 
24526
24817
  // apps/server/file-routes.ts
24527
- import { z as z80 } from "zod";
24818
+ import { z as z81 } from "zod";
24528
24819
  function registerFileRoutes(server, store) {
24529
24820
  const files = new FileRepository(store);
24530
24821
  const shared = new SharedFilesRepository(store);
@@ -24563,14 +24854,14 @@ function registerFileRoutes(server, store) {
24563
24854
  missing: files.missing(authorize(request), BlobCheckSchema.parse(request.body).hashes)
24564
24855
  }));
24565
24856
  server.put("/blobs/:hash", { ...guard, bodyLimit: MAX_BLOB_BYTES }, async (request) => {
24566
- const { hash: hash3 } = z80.object({ hash: HashSchema }).parse(request.params);
24857
+ const { hash: hash3 } = z81.object({ hash: HashSchema }).parse(request.params);
24567
24858
  if (!Buffer.isBuffer(request.body))
24568
24859
  throw Object.assign(new Error("Expected binary content"), { statusCode: 400 });
24569
24860
  return files.upload(request.headers.authorization, device(request), hash3, request.body);
24570
24861
  });
24571
24862
  server.get("/blobs/:hash", async (request, reply) => {
24572
- const { hash: hash3 } = z80.object({ hash: HashSchema }).parse(request.params);
24573
- const { view } = z80.object({ view: z80.literal("html").optional() }).parse(request.query);
24863
+ const { hash: hash3 } = z81.object({ hash: HashSchema }).parse(request.params);
24864
+ const { view } = z81.object({ view: z81.literal("html").optional() }).parse(request.query);
24574
24865
  const bytes3 = await files.download(authorizeRead(store, request), hash3);
24575
24866
  if (view === "html") return sendHtmlPreview(reply, bytes3);
24576
24867
  return reply.type("application/octet-stream").send(Buffer.from(bytes3.buffer, bytes3.byteOffset, bytes3.byteLength));
@@ -24613,7 +24904,7 @@ function registerFileRoutes(server, store) {
24613
24904
  });
24614
24905
  server.get("/files/self/operations/:operation", guard, async (request) => {
24615
24906
  const actor = authorize(request);
24616
- const { operation } = z80.object({ operation: z80.uuid() }).parse(request.params);
24907
+ const { operation } = z81.object({ operation: z81.uuid() }).parse(request.params);
24617
24908
  const row = store.db.prepare(
24618
24909
  "SELECT revision FROM file_operations WHERE workspace_id=? AND owner=? AND operation_id=?"
24619
24910
  ).get(actor.workspaceId, actor.memberId, operation);
@@ -24621,7 +24912,7 @@ function registerFileRoutes(server, store) {
24621
24912
  });
24622
24913
  server.get("/files/_project/operations/:operation", guard, async (request) => {
24623
24914
  const actor = authorize(request);
24624
- const { operation } = z80.object({ operation: z80.uuid() }).parse(request.params);
24915
+ const { operation } = z81.object({ operation: z81.uuid() }).parse(request.params);
24625
24916
  const row = store.db.prepare(
24626
24917
  "SELECT revision FROM file_operations WHERE workspace_id=? AND owner=? AND operation_id=?"
24627
24918
  ).get(actor.workspaceId, "_project", operation);
@@ -24629,7 +24920,7 @@ function registerFileRoutes(server, store) {
24629
24920
  });
24630
24921
  server.get("/files/:owner/operations/:operation", guard, async (request) => {
24631
24922
  const actor = authorize(request);
24632
- const { owner, operation } = z80.object({ owner: FileOwnerSchema, operation: z80.uuid() }).parse(request.params);
24923
+ const { owner, operation } = z81.object({ owner: FileOwnerSchema, operation: z81.uuid() }).parse(request.params);
24633
24924
  const row = store.db.prepare(
24634
24925
  "SELECT revision FROM file_operations WHERE workspace_id=? AND owner=? AND operation_id=?"
24635
24926
  ).get(actor.workspaceId, owner, operation);
@@ -24640,11 +24931,11 @@ function registerFileRoutes(server, store) {
24640
24931
  return new TaskFiles(store).resolveName(authorize(request), input.path, input.expectedHash);
24641
24932
  });
24642
24933
  server.get("/files/:owner/manifest", async (request) => {
24643
- const { owner } = z80.object({ owner: FileOwnerSchema }).parse(request.params);
24644
- const query2 = z80.object({
24645
- revision: z80.coerce.number().int().min(0).max(Number.MAX_SAFE_INTEGER).optional(),
24646
- after: z80.string().max(1024).default(""),
24647
- limit: z80.coerce.number().int().min(1).max(500).default(200)
24934
+ const { owner } = z81.object({ owner: FileOwnerSchema }).parse(request.params);
24935
+ const query2 = z81.object({
24936
+ revision: z81.coerce.number().int().min(0).max(Number.MAX_SAFE_INTEGER).optional(),
24937
+ after: z81.string().max(1024).default(""),
24938
+ limit: z81.coerce.number().int().min(1).max(500).default(200)
24648
24939
  }).parse(request.query);
24649
24940
  return files.manifest(
24650
24941
  await fileIdentity(request, owner),
@@ -24655,20 +24946,20 @@ function registerFileRoutes(server, store) {
24655
24946
  );
24656
24947
  });
24657
24948
  server.get("/files/:owner/entry", async (request) => {
24658
- const { owner } = z80.object({ owner: FileOwnerSchema }).parse(request.params);
24659
- const q = z80.object({
24949
+ const { owner } = z81.object({ owner: FileOwnerSchema }).parse(request.params);
24950
+ const q = z81.object({
24660
24951
  path: FilePathSchema,
24661
- revision: z80.coerce.number().int().min(0).max(Number.MAX_SAFE_INTEGER).optional()
24952
+ revision: z81.coerce.number().int().min(0).max(Number.MAX_SAFE_INTEGER).optional()
24662
24953
  }).parse(request.query);
24663
24954
  return files.entry(await fileIdentity(request, owner), owner, q.path, q.revision);
24664
24955
  });
24665
24956
  server.get("/files/:owner/tree", async (request) => {
24666
- const { owner } = z80.object({ owner: FileOwnerSchema }).parse(request.params);
24667
- const q = z80.object({
24668
- path: z80.union([z80.literal(""), FilePathSchema]).default(""),
24669
- revision: z80.coerce.number().int().min(0).max(Number.MAX_SAFE_INTEGER).optional(),
24670
- after: z80.string().max(255).default(""),
24671
- limit: z80.coerce.number().int().min(1).max(200).default(100)
24957
+ const { owner } = z81.object({ owner: FileOwnerSchema }).parse(request.params);
24958
+ const q = z81.object({
24959
+ path: z81.union([z81.literal(""), FilePathSchema]).default(""),
24960
+ revision: z81.coerce.number().int().min(0).max(Number.MAX_SAFE_INTEGER).optional(),
24961
+ after: z81.string().max(255).default(""),
24962
+ limit: z81.coerce.number().int().min(1).max(200).default(100)
24672
24963
  }).parse(request.query);
24673
24964
  return files.tree(
24674
24965
  await fileIdentity(request, owner),
@@ -24680,10 +24971,10 @@ function registerFileRoutes(server, store) {
24680
24971
  );
24681
24972
  });
24682
24973
  server.get("/files/:owner/changes", async (request) => {
24683
- const { owner } = z80.object({ owner: FileOwnerSchema }).parse(request.params);
24684
- const query2 = z80.object({
24685
- after: z80.coerce.number().int().min(0).max(Number.MAX_SAFE_INTEGER).default(0),
24686
- limit: z80.coerce.number().int().min(1).max(100).default(100)
24974
+ const { owner } = z81.object({ owner: FileOwnerSchema }).parse(request.params);
24975
+ const query2 = z81.object({
24976
+ after: z81.coerce.number().int().min(0).max(Number.MAX_SAFE_INTEGER).default(0),
24977
+ limit: z81.coerce.number().int().min(1).max(100).default(100)
24687
24978
  }).parse(request.query);
24688
24979
  return files.changes(await fileIdentity(request, owner), owner, query2.after, query2.limit);
24689
24980
  });
@@ -24726,7 +25017,7 @@ function clearUnread(hub, identity, scope2) {
24726
25017
 
24727
25018
  // apps/server/agents/routes.ts
24728
25019
  import { createHash as createHash29 } from "node:crypto";
24729
- import { z as z81 } from "zod";
25020
+ import { z as z82 } from "zod";
24730
25021
 
24731
25022
  // apps/server/agents/ssh-key.ts
24732
25023
  import { execFile as execFile2 } from "node:child_process";
@@ -24752,16 +25043,19 @@ async function projectSshKey(hub, project) {
24752
25043
  );
24753
25044
  publicKey = (await readFile7(path + ".pub", "utf8")).trim();
24754
25045
  }
24755
- const latest = config.secrets(project);
24756
- if (latest.sshPublicKey) return config.view(project);
24757
- if (latest.sshPrivateKey !== initial.sshPrivateKey)
24758
- throw new HubError(409, "AGENT_CONFIG_CHANGED", "SSH \u914D\u7F6E\u5DF2\u53D8\u5316\uFF0C\u8BF7\u91CD\u8BD5\u3002");
24759
- return config.save(
24760
- project,
24761
- { config: config.get(project), sshPrivateKey: await readFile7(path, "utf8") },
24762
- void 0,
24763
- publicKey
24764
- );
25046
+ const privateKey = await readFile7(path, "utf8");
25047
+ return diagnosticTransaction(hub, () => {
25048
+ const latest = config.secrets(project);
25049
+ if (latest.sshPublicKey) return config.view(project);
25050
+ if (latest.sshPrivateKey !== initial.sshPrivateKey)
25051
+ throw new HubError(409, "AGENT_CONFIG_CHANGED", "SSH \u914D\u7F6E\u5DF2\u53D8\u5316\uFF0C\u8BF7\u91CD\u8BD5\u3002");
25052
+ return config.save(
25053
+ project,
25054
+ { config: config.get(project), sshPrivateKey: privateKey },
25055
+ void 0,
25056
+ publicKey
25057
+ );
25058
+ });
24765
25059
  } finally {
24766
25060
  await rm10(directory, { recursive: true, force: true });
24767
25061
  }
@@ -24782,7 +25076,7 @@ function registerProjectAgentRoutes(server, hub) {
24782
25076
  webMutation(req);
24783
25077
  return topics.publish(authorizeWeb(hub, req), messageId(req.params));
24784
25078
  });
24785
- const messageId = (value) => z81.object({ id: z81.uuid() }).parse(value).id;
25079
+ const messageId = (value) => z82.object({ id: z82.uuid() }).parse(value).id;
24786
25080
  server.addHook("preClose", async () => {
24787
25081
  for (const stream of streams) stream.end();
24788
25082
  });
@@ -24831,20 +25125,29 @@ function registerProjectAgentRoutes(server, hub) {
24831
25125
  const url = config.get(identity.workspaceId).repositoryUrl;
24832
25126
  return new RuntimeStatus(hub).repository(identity.workspaceId, url ? fingerprint2(url) : null);
24833
25127
  });
24834
- server.put("/agents/settings", async (req) => {
24835
- webMutation(req);
24836
- const identity = authorizeWeb(hub, req);
24837
- requireSiteAdmin(identity);
24838
- const input = ProjectAgentConfigUpdateSchema.parse(req.body);
24839
- return config.save(identity.workspaceId, input, () => {
24840
- const imports = new WorkspaceImports(hub);
24841
- if (input.config.repositoryUrl)
24842
- imports.request(identity, identity.workspaceId, {
24843
- kind: "repository",
24844
- path: input.config.repositoryUrl
25128
+ server.route({
25129
+ method: ["PUT", "PATCH"],
25130
+ url: "/agents/settings",
25131
+ handler: async (req) => {
25132
+ webMutation(req);
25133
+ const identity = authorizeWeb(hub, req);
25134
+ requireSiteAdmin(identity);
25135
+ const project = identity.workspaceId;
25136
+ return diagnosticTransaction(hub, () => {
25137
+ const { refreshRepositoryImport, ...input } = req.method === "PATCH" ? ProjectAgentConfigPatchSchema.parse(req.body) : { ...ProjectAgentConfigUpdateSchema.parse(req.body), refreshRepositoryImport: true };
25138
+ const next = ProjectAgentConfigSchema.parse({
25139
+ ...req.method === "PATCH" ? config.get(project) : {},
25140
+ ...input.config
24845
25141
  });
24846
- else imports.cancelRepository(identity.workspaceId);
24847
- });
25142
+ return config.save(project, { ...input, config: next }, () => {
25143
+ if (!refreshRepositoryImport && input.config.repositoryUrl === void 0) return;
25144
+ const imports = new WorkspaceImports(hub);
25145
+ if (next.repositoryUrl)
25146
+ imports.request(identity, project, { kind: "repository", path: next.repositoryUrl });
25147
+ else imports.cancelRepository(project);
25148
+ });
25149
+ });
25150
+ }
24848
25151
  });
24849
25152
  server.post("/agents/repository/check", async (req) => {
24850
25153
  webMutation(req);
@@ -24935,7 +25238,7 @@ data: ${event.data}
24935
25238
  server.post("/agents/chats/:id/read", async (req) => {
24936
25239
  webMutation(req);
24937
25240
  const identity = authorizeWeb(hub, req);
24938
- const { cursor } = z81.object({ cursor: z81.number().int().nonnegative() }).strict().parse(req.body);
25241
+ const { cursor } = z82.object({ cursor: z82.number().int().nonnegative() }).strict().parse(req.body);
24939
25242
  const id = messageId(req.params);
24940
25243
  markChatRead(hub, identity, id, cursor);
24941
25244
  return { ok: true };
@@ -24943,15 +25246,20 @@ data: ${event.data}
24943
25246
  server.get("/agents/outbox", async (req) => store.messages(authorizeWeb(hub, req)));
24944
25247
  server.post("/communication/read", async (req) => {
24945
25248
  webMutation(req);
24946
- const { scope: scope2 } = z81.object({ scope: z81.enum(["messages", "channels"]) }).strict().parse(req.body);
25249
+ const { scope: scope2 } = z82.object({ scope: z82.enum(["messages", "channels"]) }).strict().parse(req.body);
24947
25250
  return clearUnread(hub, authorizeWeb(hub, req), scope2);
24948
25251
  });
24949
25252
  server.get("/communication/unread", async (req) => {
24950
25253
  const identity = authorizeWeb(hub, req);
25254
+ const routing = new EventRouting(hub);
24951
25255
  return {
24952
25256
  messages: store.chats(identity).chats.filter((c) => "unread" in c && c.unread).length + store.messages(identity).messages.filter((m) => !m.conversationId && !m.readAt && !m.archivedAt).length,
24953
25257
  channels: topics.list(identity).topics.filter((t) => t.unread).length,
24954
- computers: new MemberSessions(hub).list(identity).filter((s) => !s.hidden && s.unread).length
25258
+ computers: new MemberSessions(hub).unreadReminders(
25259
+ identity,
25260
+ routing.computerReminder(identity, computerCompletionCategory).notify,
25261
+ routing.computerReminder(identity, computerQuestionCategory).notify
25262
+ )
24955
25263
  };
24956
25264
  });
24957
25265
  server.get("/agents/outbox/unread", async (req) => {
@@ -25067,39 +25375,39 @@ function registerBootstrapRoutes(server, hub) {
25067
25375
  }
25068
25376
 
25069
25377
  // apps/server/client-access.ts
25070
- import { z as z83 } from "zod";
25378
+ import { z as z84 } from "zod";
25071
25379
 
25072
25380
  // packages/protocol/client-access.ts
25073
- import { z as z82 } from "zod";
25074
- var ConnectSecretSchema = z82.string().regex(/^[a-f0-9]{64}$/);
25075
- var BrowserConnectRequestSchema = z82.object({
25076
- id: z82.uuid(),
25381
+ import { z as z83 } from "zod";
25382
+ var ConnectSecretSchema = z83.string().regex(/^[a-f0-9]{64}$/);
25383
+ var BrowserConnectRequestSchema = z83.object({
25384
+ id: z83.uuid(),
25077
25385
  projectId: NameSchema,
25078
25386
  deviceId: DeviceIdSchema,
25079
25387
  secret: ConnectSecretSchema,
25080
- label: z82.string().min(1).max(255)
25388
+ label: z83.string().min(1).max(255)
25081
25389
  }).strict();
25082
- var BrowserConnectStartSchema = z82.object({
25083
- id: z82.uuid(),
25084
- expiresAt: z82.number(),
25085
- verificationUrl: z82.string().url().optional()
25390
+ var BrowserConnectStartSchema = z83.object({
25391
+ id: z83.uuid(),
25392
+ expiresAt: z83.number(),
25393
+ verificationUrl: z83.string().url().optional()
25086
25394
  });
25087
- var BrowserConnectPollSchema = z82.discriminatedUnion("state", [
25088
- z82.object({ state: z82.literal("pending") }),
25089
- z82.object({ state: z82.literal("approved"), memberId: NameSchema })
25395
+ var BrowserConnectPollSchema = z83.discriminatedUnion("state", [
25396
+ z83.object({ state: z83.literal("pending") }),
25397
+ z83.object({ state: z83.literal("approved"), memberId: NameSchema })
25090
25398
  ]);
25091
- var BrowserConnectInfoSchema = z82.object({
25092
- projectName: z82.string(),
25093
- label: z82.string(),
25399
+ var BrowserConnectInfoSchema = z83.object({
25400
+ projectName: z83.string(),
25401
+ label: z83.string(),
25094
25402
  approvedBy: NameSchema.nullable(),
25095
- expiresAt: z82.number()
25403
+ expiresAt: z83.number()
25096
25404
  });
25097
25405
 
25098
25406
  // apps/server/client-access.ts
25099
25407
  function registerClientAccess(server, store) {
25100
25408
  const project = new ProjectRepository(store);
25101
25409
  const read = (id) => {
25102
- const row = store.db.prepare("SELECT * FROM device_connect_requests WHERE id=?").get(z83.uuid().parse(id));
25410
+ const row = store.db.prepare("SELECT * FROM device_connect_requests WHERE id=?").get(z84.uuid().parse(id));
25103
25411
  if (!row || Number(row.expires_at) <= Date.now())
25104
25412
  throw new HubError(410, "CONNECT_EXPIRED", "\u8FDE\u63A5\u8BF7\u6C42\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u8FD0\u884C teammy connect\u3002");
25105
25413
  return row;
@@ -25134,7 +25442,7 @@ function registerClientAccess(server, store) {
25134
25442
  };
25135
25443
  });
25136
25444
  server.post("/api/v1/devices/connect/:id/poll", async (request) => {
25137
- const { secret } = z83.object({ secret: ConnectSecretSchema }).strict().parse(request.body);
25445
+ const { secret } = z84.object({ secret: ConnectSecretSchema }).strict().parse(request.body);
25138
25446
  const row = read(request.params.id);
25139
25447
  if (row.secret_hash !== digest(secret))
25140
25448
  throw new HubError(
@@ -25178,19 +25486,21 @@ function registerClientAccess(server, store) {
25178
25486
  }
25179
25487
 
25180
25488
  // apps/server/client-release.ts
25181
- import { z as z84 } from "zod";
25182
- var ReleaseSchema = z84.object({
25183
- name: z84.literal("@teammy/cli"),
25184
- "dist-tags": z84.object({
25185
- latest: z84.string().regex(/^\d+\.\d+\.\d+(?:-[\da-z.-]+)?(?:\+[\da-z.-]+)?$/i)
25489
+ import { z as z85 } from "zod";
25490
+ import { readFile as readFile8 } from "node:fs/promises";
25491
+ import { join as join30 } from "node:path";
25492
+ var ReleaseSchema = z85.object({
25493
+ name: z85.literal("@teammy/cli"),
25494
+ "dist-tags": z85.object({
25495
+ latest: z85.string().regex(/^\d+\.\d+\.\d+(?:-[\da-z.-]+)?(?:\+[\da-z.-]+)?$/i)
25186
25496
  }),
25187
- versions: z84.record(z84.string(), z84.unknown())
25497
+ versions: z85.record(z85.string(), z85.unknown())
25188
25498
  });
25189
- function registerClientRelease(server) {
25499
+ function registerClientRelease(server, version2, dataDir) {
25190
25500
  let cached;
25191
25501
  let expiresAt = 0;
25192
25502
  let pending;
25193
- server.get("/api/v1/client/latest", async () => {
25503
+ async function latest() {
25194
25504
  if (Date.now() >= expiresAt) {
25195
25505
  pending ??= (async () => {
25196
25506
  try {
@@ -25199,10 +25509,10 @@ function registerClientRelease(server) {
25199
25509
  signal: AbortSignal.timeout(5e3)
25200
25510
  });
25201
25511
  if (!response.ok) throw new Error("Registry unavailable.");
25202
- const release = ReleaseSchema.parse(await response.json());
25203
- const version2 = release["dist-tags"].latest;
25204
- if (!Object.hasOwn(release.versions, version2)) throw new Error("Latest release missing.");
25205
- cached = { version: version2, versions: Object.keys(release.versions) };
25512
+ const release2 = ReleaseSchema.parse(await response.json());
25513
+ const version3 = release2["dist-tags"].latest;
25514
+ if (!Object.hasOwn(release2.versions, version3)) throw new Error("Latest release missing.");
25515
+ cached = { version: version3, versions: Object.keys(release2.versions) };
25206
25516
  expiresAt = Date.now() + 5 * 6e4;
25207
25517
  } catch {
25208
25518
  cached = void 0;
@@ -25216,11 +25526,25 @@ function registerClientRelease(server) {
25216
25526
  if (!cached)
25217
25527
  throw new HubError(503, "CLIENT_RELEASE_UNAVAILABLE", "\u6682\u65F6\u65E0\u6CD5\u83B7\u53D6\u6700\u65B0\u7248\u5BA2\u6237\u7AEF\u7248\u672C\u3002");
25218
25528
  return cached;
25219
- });
25529
+ }
25530
+ server.get("/api/v1/client/latest", latest);
25531
+ return async (running) => {
25532
+ let target2 = true ? "0.2.19" : version2;
25533
+ if (dataDir) {
25534
+ try {
25535
+ target2 = (await readFile8(join30(dataDir, "client-update-version"), "utf8")).trim();
25536
+ } catch (error) {
25537
+ if (error.code !== "ENOENT") throw error;
25538
+ }
25539
+ }
25540
+ if (!stableVersion.test(target2) || !stableVersion.test(running) || compareVersions(target2, running) <= 0)
25541
+ return null;
25542
+ return (await latest()).versions.includes(target2) ? target2 : null;
25543
+ };
25220
25544
  }
25221
25545
 
25222
25546
  // apps/server/wecom/routes.ts
25223
- import { z as z85 } from "zod";
25547
+ import { z as z86 } from "zod";
25224
25548
 
25225
25549
  // apps/server/wecom/runtime.ts
25226
25550
  import { randomUUID as randomUUID40 } from "node:crypto";
@@ -26017,6 +26341,20 @@ var WecomRuntime = class {
26017
26341
  const channel = delivery.chat_type === 3 ? JSON.parse(delivery.channel_json) : null;
26018
26342
  const target2 = channel ? `channel:${delivery.external_id}:${channel.conversationId}` : `${delivery.chat_type ?? 1}:${delivery.external_id}`;
26019
26343
  if (targets.has(target2)) continue;
26344
+ const part = delivery.kind === computerCompletionCategory && /:(\d+)$/.exec(delivery.source_id);
26345
+ if (part) {
26346
+ const base = delivery.source_id.slice(0, part.index);
26347
+ const previous = Number(part[1]) - 1;
26348
+ if (!this.hub.db.prepare(
26349
+ "SELECT 1 FROM wecom_deliveries WHERE bot_id=? AND external_id=? AND kind=? AND source_id=? AND state='sent'"
26350
+ ).get(
26351
+ delivery.bot_id,
26352
+ delivery.external_id,
26353
+ delivery.kind,
26354
+ previous ? `${base}:${previous}` : base
26355
+ ))
26356
+ continue;
26357
+ }
26020
26358
  if (channel?.action === "post" && this.hub.db.prepare(
26021
26359
  `SELECT 1 FROM wecom_deliveries WHERE bot_id=? AND external_id=? AND chat_type=3 AND state='pending' AND json_extract(channel_json,'$.action')='post' AND rowid<(SELECT rowid FROM wecom_deliveries WHERE id=?)`
26022
26360
  ).get(delivery.bot_id, delivery.external_id, delivery.id))
@@ -26101,7 +26439,7 @@ function registerWecom(server, hub, env, factory) {
26101
26439
  webMutation(req);
26102
26440
  return channels2.bind(
26103
26441
  authorizeWeb(hub, req),
26104
- z85.object({ topicId: z85.string().min(1).nullable() }).strict().parse(req.body).topicId
26442
+ z86.object({ topicId: z86.string().min(1).nullable() }).strict().parse(req.body).topicId
26105
26443
  );
26106
26444
  });
26107
26445
  server.get(`${base}/groups`, async (req) => groups.list(authorizeWeb(hub, req)));
@@ -26113,7 +26451,7 @@ function registerWecom(server, hub, env, factory) {
26113
26451
  webMutation(req);
26114
26452
  return groups.remove(
26115
26453
  authorizeWeb(hub, req),
26116
- z85.object({ chatId: z85.string().min(1) }).parse(req.params).chatId
26454
+ z86.object({ chatId: z86.string().min(1) }).parse(req.params).chatId
26117
26455
  );
26118
26456
  });
26119
26457
  server.get(base, async (req) => store.binding(authorizeWeb(hub, req)));
@@ -26255,20 +26593,20 @@ function registerTaiAuth(server, store, env) {
26255
26593
  }
26256
26594
 
26257
26595
  // packages/protocol/deployment-migration.ts
26258
- import { z as z86 } from "zod";
26596
+ import { z as z87 } from "zod";
26259
26597
  var ANYDEV_MIGRATION = {
26260
26598
  id: "anydev-20261112",
26261
26599
  from: "https://ms-cm2lcn7d-100034032793-sw.gw.ap-zhongwei.ti.tencentcs.com/ms-cm2lcn7d",
26262
26600
  previous: "https://teammy.woa.com/client",
26263
26601
  to: "http://teammy.woa.com/client"
26264
26602
  };
26265
- var DeploymentMigrationSchema = z86.object({
26266
- migration: z86.string(),
26603
+ var DeploymentMigrationSchema = z87.object({
26604
+ migration: z87.string(),
26267
26605
  binding: BindingSchema
26268
26606
  });
26269
26607
 
26270
26608
  // apps/server/messaging/routes.ts
26271
- import { z as z87 } from "zod";
26609
+ import { z as z88 } from "zod";
26272
26610
  function registerEventRouting(server, hub) {
26273
26611
  const routing = new EventRouting(hub);
26274
26612
  server.get("/web/event-routing", async (req) => routing.settings(authorizeWeb(hub, req)));
@@ -26314,7 +26652,7 @@ function registerEventRouting(server, hub) {
26314
26652
  webMutation(req);
26315
26653
  return routing.reassign(
26316
26654
  authorizeWeb(hub, req),
26317
- z87.object({ id: z87.uuid() }).parse(req.params).id,
26655
+ z88.object({ id: z88.uuid() }).parse(req.params).id,
26318
26656
  req.body
26319
26657
  );
26320
26658
  });
@@ -26326,20 +26664,20 @@ function registerEventRouting(server, hub) {
26326
26664
  "/event-hooks/:id",
26327
26665
  async (req) => routing.setHook(
26328
26666
  authorizeDevice(hub, req),
26329
- z87.object({ id: z87.uuid() }).parse(req.params).id,
26330
- z87.object({ enabled: z87.boolean() }).strict().parse(req.body).enabled
26667
+ z88.object({ id: z88.uuid() }).parse(req.params).id,
26668
+ z88.object({ enabled: z88.boolean() }).strict().parse(req.body).enabled
26331
26669
  )
26332
26670
  );
26333
26671
  server.patch("/web/event-hooks/:id", async (req) => {
26334
26672
  webMutation(req);
26335
26673
  return routing.setHook(
26336
26674
  authorizeWeb(hub, req),
26337
- z87.object({ id: z87.uuid() }).parse(req.params).id,
26338
- z87.object({ enabled: z87.boolean() }).strict().parse(req.body).enabled
26675
+ z88.object({ id: z88.uuid() }).parse(req.params).id,
26676
+ z88.object({ enabled: z88.boolean() }).strict().parse(req.body).enabled
26339
26677
  );
26340
26678
  });
26341
26679
  server.get("/web/channel-topics/:id/subscription", async (req) => {
26342
- const identity = authorizeWeb(hub, req), { id } = z87.object({ id: z87.uuid() }).parse(req.params);
26680
+ const identity = authorizeWeb(hub, req), { id } = z88.object({ id: z88.uuid() }).parse(req.params);
26343
26681
  new AgentStore(hub).ownedChat(identity, id);
26344
26682
  if (!new WebChannels(hub).isTopic(identity.workspaceId, id))
26345
26683
  throw new HubError(404, "TOPIC_NOT_FOUND", "\u8BDD\u9898\u4E0D\u5B58\u5728\u3002");
@@ -26351,11 +26689,11 @@ function registerEventRouting(server, hub) {
26351
26689
  });
26352
26690
  server.put("/web/channel-topics/:id/subscription", async (req) => {
26353
26691
  webMutation(req);
26354
- const identity = authorizeWeb(hub, req), { id } = z87.object({ id: z87.uuid() }).parse(req.params);
26692
+ const identity = authorizeWeb(hub, req), { id } = z88.object({ id: z88.uuid() }).parse(req.params);
26355
26693
  new AgentStore(hub).ownedChat(identity, id);
26356
26694
  if (!new WebChannels(hub).isTopic(identity.workspaceId, id))
26357
26695
  throw new HubError(404, "TOPIC_NOT_FOUND", "\u8BDD\u9898\u4E0D\u5B58\u5728\u3002");
26358
- const { subscribed } = z87.object({ subscribed: z87.boolean() }).strict().parse(req.body);
26696
+ const { subscribed } = z88.object({ subscribed: z88.boolean() }).strict().parse(req.body);
26359
26697
  if (subscribed)
26360
26698
  hub.db.prepare("INSERT OR IGNORE INTO routing_topic_subscriptions VALUES(?,?,?)").run(identity.workspaceId, identity.memberId, id);
26361
26699
  else
@@ -26365,7 +26703,7 @@ function registerEventRouting(server, hub) {
26365
26703
  return { subscribed };
26366
26704
  });
26367
26705
  server.get("/web/local-agent-sessions/:id/group-sync", async (req) => {
26368
- const identity = authorizeWeb(hub, req), { id } = z87.object({ id: ExecutionRef }).parse(req.params);
26706
+ const identity = authorizeWeb(hub, req), { id } = z88.object({ id: ExecutionRef }).parse(req.params);
26369
26707
  new MemberSessions(hub).get(identity, id);
26370
26708
  return {
26371
26709
  enabled: !!hub.db.prepare("SELECT group_sync FROM member_agent_sessions WHERE project_id=? AND id=?").get(identity.workspaceId, id)?.group_sync
@@ -26373,9 +26711,9 @@ function registerEventRouting(server, hub) {
26373
26711
  });
26374
26712
  server.put("/web/local-agent-sessions/:id/group-sync", async (req) => {
26375
26713
  webMutation(req);
26376
- const identity = authorizeWeb(hub, req), { id } = z87.object({ id: ExecutionRef }).parse(req.params);
26714
+ const identity = authorizeWeb(hub, req), { id } = z88.object({ id: ExecutionRef }).parse(req.params);
26377
26715
  new MemberSessions(hub).get(identity, id);
26378
- const { enabled } = z87.object({ enabled: z87.boolean() }).strict().parse(req.body);
26716
+ const { enabled } = z88.object({ enabled: z88.boolean() }).strict().parse(req.body);
26379
26717
  hub.db.prepare("UPDATE member_agent_sessions SET group_sync=? WHERE project_id=? AND id=?").run(Number(enabled), identity.workspaceId, id);
26380
26718
  return { enabled };
26381
26719
  });
@@ -26388,41 +26726,41 @@ function registerHookInbox(server, hub) {
26388
26726
  async (req) => routing.pollHook(token(req.headers.authorization))
26389
26727
  );
26390
26728
  server.post("/api/v1/event-hooks/inbox/:id/ack", async (req) => {
26391
- const { id } = z87.object({ id: z87.uuid() }).parse(req.params);
26729
+ const { id } = z88.object({ id: z88.uuid() }).parse(req.params);
26392
26730
  return routing.ackHook(token(req.headers.authorization), id);
26393
26731
  });
26394
26732
  }
26395
26733
 
26396
26734
  // apps/server/member-execution/routes.ts
26397
- import { z as z90 } from "zod";
26735
+ import { z as z91 } from "zod";
26398
26736
 
26399
26737
  // apps/server/member-execution/consult.ts
26400
- import { z as z89 } from "zod";
26738
+ import { z as z90 } from "zod";
26401
26739
 
26402
26740
  // packages/protocol/external-tools.ts
26403
- import { z as z88 } from "zod";
26404
- var ToolCatalogSchema = z88.object({
26405
- tools: z88.array(
26406
- z88.object({
26407
- name: z88.string(),
26408
- description: z88.string(),
26409
- inputSchema: z88.object({ type: z88.literal("object") }).passthrough(),
26410
- annotations: z88.object({
26411
- readOnlyHint: z88.boolean(),
26412
- destructiveHint: z88.boolean(),
26413
- idempotentHint: z88.boolean(),
26414
- openWorldHint: z88.boolean()
26741
+ import { z as z89 } from "zod";
26742
+ var ToolCatalogSchema = z89.object({
26743
+ tools: z89.array(
26744
+ z89.object({
26745
+ name: z89.string(),
26746
+ description: z89.string(),
26747
+ inputSchema: z89.object({ type: z89.literal("object") }).passthrough(),
26748
+ annotations: z89.object({
26749
+ readOnlyHint: z89.boolean(),
26750
+ destructiveHint: z89.boolean(),
26751
+ idempotentHint: z89.boolean(),
26752
+ openWorldHint: z89.boolean()
26415
26753
  })
26416
26754
  })
26417
26755
  )
26418
26756
  });
26419
- var ToolResultSchema = z88.object({ result: z88.unknown() });
26420
- var AskTeammySchema = z88.object({
26421
- text: z88.string().trim().min(1),
26422
- conversationId: z88.uuid().optional(),
26423
- requestId: z88.string().trim().min(1).max(200)
26757
+ var ToolResultSchema = z89.object({ result: z89.unknown() });
26758
+ var AskTeammySchema = z89.object({
26759
+ text: z89.string().trim().min(1),
26760
+ conversationId: z89.uuid().optional(),
26761
+ requestId: z89.string().trim().min(1).max(200)
26424
26762
  }).strict();
26425
- var TeammyReplyQuerySchema = z88.object({ conversationId: z88.uuid(), runId: z88.uuid() }).strict();
26763
+ var TeammyReplyQuerySchema = z89.object({ conversationId: z89.uuid(), runId: z89.uuid() }).strict();
26426
26764
 
26427
26765
  // apps/server/member-execution/team-consultations.ts
26428
26766
  var TeamConsultations = class {
@@ -26471,14 +26809,14 @@ var TeamConsultations = class {
26471
26809
  };
26472
26810
 
26473
26811
  // apps/server/member-execution/consult.ts
26474
- var ConsultSchema = z89.object({
26812
+ var ConsultSchema = z90.object({
26475
26813
  inputId: ExecutionRef,
26476
- requestId: z89.string().min(1).max(160),
26477
- text: z89.string().trim().min(1),
26478
- conversationId: z89.uuid().optional()
26814
+ requestId: z90.string().min(1).max(160),
26815
+ text: z90.string().trim().min(1),
26816
+ conversationId: z90.uuid().optional()
26479
26817
  }).strict();
26480
26818
  function readTeamConsultation(hub, identity, body) {
26481
- const value = z89.object({ conversationId: z89.uuid(), runId: z89.uuid() }).strict().parse(body);
26819
+ const value = z90.object({ conversationId: z90.uuid(), runId: z90.uuid() }).strict().parse(body);
26482
26820
  const details2 = hub.db.prepare("SELECT details_json FROM agent_run_details WHERE run_id=?").get(value.runId);
26483
26821
  const input = details2 && JSON.parse(String(details2.details_json)).localExecution?.inputId;
26484
26822
  if (!input) throw new HubError(404, "TEAM_CONSULTATION_NOT_FOUND", "\u627E\u4E0D\u5230\u6258\u7BA1\u54A8\u8BE2\u3002");
@@ -26530,7 +26868,8 @@ function registerMemberExecution(server, hub, previews) {
26530
26868
  });
26531
26869
  server.get("/web/local-agent-sessions/:id/events", async (request, reply) => {
26532
26870
  const identity = authorizeWeb(hub, request), session = id(request.params);
26533
- let snapshot = sessions2.chat(identity, session);
26871
+ const updatesOnly = z91.object({ updates: z91.literal("1").optional() }).parse(request.query).updates === "1";
26872
+ let cursor = sessions2.eventCursor(identity, session);
26534
26873
  reply.hijack();
26535
26874
  const response = reply.raw;
26536
26875
  response.writeHead(200, {
@@ -26539,21 +26878,29 @@ function registerMemberExecution(server, hub, previews) {
26539
26878
  connection: "keep-alive",
26540
26879
  "x-accel-buffering": "no"
26541
26880
  });
26542
- const send2 = () => response.write(
26543
- `id: ${snapshot.cursor}
26881
+ const send2 = () => {
26882
+ if (updatesOnly) response.write(`id: ${cursor}
26883
+ event: change
26884
+ data: ${cursor}
26885
+
26886
+ `);
26887
+ else
26888
+ response.write(
26889
+ `id: ${cursor}
26544
26890
  event: snapshot
26545
- data: ${JSON.stringify(snapshot)}
26891
+ data: ${JSON.stringify(sessions2.chat(identity, session, { from: 1 }))}
26546
26892
 
26547
26893
  `
26548
- );
26894
+ );
26895
+ };
26549
26896
  streams.add(response);
26550
26897
  send2();
26551
26898
  let ping = Date.now();
26552
26899
  const timer2 = setInterval(() => {
26553
26900
  try {
26554
- const next = sessions2.chat(authorizeWeb(hub, request), session);
26555
- if (next.cursor > snapshot.cursor) {
26556
- snapshot = next;
26901
+ const next = sessions2.eventCursor(authorizeWeb(hub, request), session);
26902
+ if (next !== cursor) {
26903
+ cursor = next;
26557
26904
  send2();
26558
26905
  }
26559
26906
  if (Date.now() - ping > 15e3) {
@@ -26648,10 +26995,15 @@ data: ${JSON.stringify(snapshot)}
26648
26995
  webMutation(request);
26649
26996
  return sessions2.directorySettings(authorizeWeb(hub, request), id(request.params), request.body);
26650
26997
  });
26651
- server.get(
26652
- "/web/local-agent-sessions/:id",
26653
- async (request) => sessions2.chat(authorizeWeb(hub, request), id(request.params))
26654
- );
26998
+ server.get("/web/local-agent-sessions/:id", async (request) => {
26999
+ const seq = z91.coerce.number().int().positive().max(Number.MAX_SAFE_INTEGER);
27000
+ const window = z91.object({
27001
+ before: seq.optional(),
27002
+ from: seq.optional(),
27003
+ question: z91.string().max(500).optional()
27004
+ }).parse(request.query);
27005
+ return sessions2.chat(authorizeWeb(hub, request), id(request.params), window);
27006
+ });
26655
27007
  server.put("/web/local-agent-sessions/:id/metadata", async (request) => {
26656
27008
  webMutation(request);
26657
27009
  return sessions2.metadata(authorizeWeb(hub, request), id(request.params), request.body);
@@ -26659,7 +27011,7 @@ data: ${JSON.stringify(snapshot)}
26659
27011
  server.post("/web/local-agents/:id/history", async (request) => {
26660
27012
  webMutation(request);
26661
27013
  const identity = authorizeWeb(hub, request);
26662
- const value = z90.object({ id: z90.uuid(), argument: z90.string() }).parse(request.body);
27014
+ const value = z91.object({ id: z91.uuid(), argument: z91.string() }).parse(request.body);
26663
27015
  return sessions2.command(identity, sessions2.directoryHistory(identity, id(request.params)), {
26664
27016
  ...value,
26665
27017
  kind: "history"
@@ -26667,7 +27019,7 @@ data: ${JSON.stringify(snapshot)}
26667
27019
  });
26668
27020
  server.get("/web/local-agents/:id/history/:command", async (request) => {
26669
27021
  const identity = authorizeWeb(hub, request);
26670
- const params2 = z90.object({ id: z90.string(), command: z90.string() }).parse(request.params);
27022
+ const params2 = z91.object({ id: z91.string(), command: z91.string() }).parse(request.params);
26671
27023
  return sessions2.history(
26672
27024
  identity,
26673
27025
  sessions2.directoryHistory(identity, params2.id, params2.command),
@@ -26683,11 +27035,11 @@ data: ${JSON.stringify(snapshot)}
26683
27035
  return sessions2.read(authorizeWeb(hub, request), id(request.params));
26684
27036
  });
26685
27037
  server.get("/web/local-agent-sessions/:id/diff/:command", async (request) => {
26686
- const params2 = z90.object({ id: z90.string(), command: z90.uuid() }).parse(request.params);
27038
+ const params2 = z91.object({ id: z91.string(), command: z91.uuid() }).parse(request.params);
26687
27039
  return sessions2.diff(authorizeWeb(hub, request), params2.id, params2.command);
26688
27040
  });
26689
27041
  server.get("/web/local-agent-sessions/:id/history/:command", async (request) => {
26690
- const params2 = z90.object({ id: z90.string(), command: z90.uuid() }).parse(request.params);
27042
+ const params2 = z91.object({ id: z91.string(), command: z91.uuid() }).parse(request.params);
26691
27043
  return sessions2.history(authorizeWeb(hub, request), params2.id, params2.command);
26692
27044
  });
26693
27045
  server.post("/web/local-agent-sessions/:id/commands", async (request) => {
@@ -26697,13 +27049,13 @@ data: ${JSON.stringify(snapshot)}
26697
27049
  server.post("/web/local-agent-sessions/:id/messages", async (request) => {
26698
27050
  webMutation(request);
26699
27051
  const identity = authorizeWeb(hub, request), session = sessions2.get(identity, id(request.params));
26700
- const value = z90.object({
26701
- id: z90.uuid(),
26702
- body: z90.string().trim().max(2e5),
26703
- delivery: z90.enum(["auto", "queue"]).optional(),
26704
- images: z90.array(z90.uuid()).max(MAX_SESSION_IMAGES).default([]),
26705
- attachments: z90.array(z90.uuid()).max(MAX_SESSION_IMAGES).default([]),
26706
- skills: z90.array(z90.object({ name: z90.string(), path: z90.string() })).optional()
27052
+ const value = z91.object({
27053
+ id: z91.uuid(),
27054
+ body: z91.string().trim().max(2e5),
27055
+ delivery: z91.enum(["auto", "queue"]).optional(),
27056
+ images: z91.array(z91.uuid()).max(MAX_SESSION_IMAGES).default([]),
27057
+ attachments: z91.array(z91.uuid()).max(MAX_SESSION_IMAGES).default([]),
27058
+ skills: z91.array(z91.object({ name: z91.string(), path: z91.string() })).optional()
26707
27059
  }).parse(request.body);
26708
27060
  if (!store.sessionCapable(identity, session.directory))
26709
27061
  throw new HubError(409, "CLIENT_UPGRADE", "\u8BF7\u5347\u7EA7\u5BA2\u6237\u7AEF\u540E\u4F7F\u7528\u7535\u8111\u4F1A\u8BDD\u3002");
@@ -26757,7 +27109,7 @@ data: ${JSON.stringify(snapshot)}
26757
27109
  }
26758
27110
  });
26759
27111
  });
26760
- const questionParams = z90.object({ id: z90.string(), question: z90.string() });
27112
+ const questionParams = z91.object({ id: z91.string(), question: z91.string() });
26761
27113
  server.post("/web/local-agent-sessions/:id/questions/:question/presented", async (request) => {
26762
27114
  webMutation(request);
26763
27115
  const params2 = questionParams.parse(request.params);
@@ -26766,13 +27118,13 @@ data: ${JSON.stringify(snapshot)}
26766
27118
  server.post("/web/local-agent-sessions/:id/questions/:question/answers", async (request) => {
26767
27119
  webMutation(request);
26768
27120
  const identity = authorizeWeb(hub, request), params2 = questionParams.parse(request.params);
26769
- const value = z90.object({
26770
- id: z90.uuid(),
26771
- body: z90.string().trim().min(1),
26772
- decision: z90.boolean().optional(),
26773
- actionId: z90.string().max(100).optional(),
26774
- selections: z90.record(z90.string(), z90.array(z90.string().max(500)).max(20)).optional(),
26775
- answers: z90.record(z90.string(), z90.string().max(12e3)).optional()
27121
+ const value = z91.object({
27122
+ id: z91.uuid(),
27123
+ body: z91.string().trim().min(1),
27124
+ decision: z91.boolean().optional(),
27125
+ actionId: z91.string().max(100).optional(),
27126
+ selections: z91.record(z91.string(), z91.array(z91.string().max(500)).max(20)).optional(),
27127
+ answers: z91.record(z91.string(), z91.string().max(12e3)).optional()
26776
27128
  }).parse(request.body);
26777
27129
  const session = sessions2.get(identity, params2.id), question = sessions2.question(identity, params2.id, params2.question);
26778
27130
  const content = JSON.parse(String(question.content_json));
@@ -26847,7 +27199,7 @@ data: ${JSON.stringify(snapshot)}
26847
27199
  "/local-agent/event-reply",
26848
27200
  async (request) => replyToRoutedRequest(hub, authorizeDevice(hub, request), request.body)
26849
27201
  );
26850
- const id = (params2) => z90.object({ id: ExecutionRef }).parse(params2).id;
27202
+ const id = (params2) => z91.object({ id: ExecutionRef }).parse(params2).id;
26851
27203
  server.get("/local-agent/directories", async (request) => ({
26852
27204
  directories: store.directories(authorizeDevice(hub, request)).map(({ deviceId: _, ...directory }) => directory)
26853
27205
  }));
@@ -26865,7 +27217,7 @@ data: ${JSON.stringify(snapshot)}
26865
27217
  );
26866
27218
  server.get("/local-agent/inputs", async (request) => {
26867
27219
  const identity = authorizeDevice(hub, request);
26868
- const query2 = z90.object({ instance: z90.uuid(), cursor: z90.coerce.number().int().nonnegative().default(0) }).parse(request.query);
27220
+ const query2 = z91.object({ instance: z91.uuid(), cursor: z91.coerce.number().int().nonnegative().default(0) }).parse(request.query);
26869
27221
  return store.poll(identity, query2.instance, query2.cursor);
26870
27222
  });
26871
27223
  server.get(
@@ -26903,10 +27255,10 @@ data: ${JSON.stringify(snapshot)}
26903
27255
  server.get("/web/local-agents", async (request) => ({
26904
27256
  directories: store.directories(authorizeWeb(hub, request))
26905
27257
  }));
26906
- const codeInput = z90.object({
27258
+ const codeInput = z91.object({
26907
27259
  directory: ExecutionRef,
26908
27260
  session: ExecutionRef.optional(),
26909
- expectedRevision: z90.number().int().nonnegative()
27261
+ expectedRevision: z91.number().int().nonnegative()
26910
27262
  }).strict();
26911
27263
  server.post("/web/local-agent-bindings/codes", async (request) => {
26912
27264
  webMutation(request);
@@ -26940,7 +27292,7 @@ data: ${JSON.stringify(snapshot)}
26940
27292
  async (request) => bridge.messageStatus(authorizeDevice(hub, request), id(request.params))
26941
27293
  );
26942
27294
  server.post("/local-agent/questions/:id/reserve", async (request) => {
26943
- const value = z90.object({ replyContext: ExecutionRef }).strict().parse(request.body);
27295
+ const value = z91.object({ replyContext: ExecutionRef }).strict().parse(request.body);
26944
27296
  return bridge.reserveQuestion(
26945
27297
  authorizeDevice(hub, request),
26946
27298
  id(request.params),
@@ -27078,7 +27430,7 @@ function buildServer(options) {
27078
27430
  return reply.code(status).send(body);
27079
27431
  });
27080
27432
  server.get("/healthz", async () => ({ status: "ok" }));
27081
- registerClientRelease(server);
27433
+ const clientUpdateTarget = registerClientRelease(server, options.version, options.dataDir);
27082
27434
  server.get("/api/v1/server", async () => ({
27083
27435
  name: "teammy",
27084
27436
  version: options.version,
@@ -27122,6 +27474,7 @@ function buildServer(options) {
27122
27474
  "local-terminals-v1",
27123
27475
  "local-agent-session-routing-v1",
27124
27476
  "local-session-activity-v1",
27477
+ "local-session-question-delivery-v1",
27125
27478
  "local-agent-providers-v1",
27126
27479
  "event-routing-v1",
27127
27480
  "internal-team-consult-v1"
@@ -27156,7 +27509,7 @@ function buildServer(options) {
27156
27509
  registerProjectScopeRoutes(scope2, store);
27157
27510
  registerAiJobRoutes(scope2, store);
27158
27511
  registerTaskRoutes(scope2, store);
27159
- registerControlRoutes(scope2, store);
27512
+ registerControlRoutes(scope2, store, clientUpdateTarget);
27160
27513
  registerFileRoutes(scope2, store);
27161
27514
  registerMaterialRoutes(scope2, store);
27162
27515
  registerMemoryRoutes(scope2, store);
@@ -27183,7 +27536,7 @@ function buildServer(options) {
27183
27536
 
27184
27537
  // apps/server/main.ts
27185
27538
  import { homedir } from "node:os";
27186
- import { join as join30, resolve as resolve6 } from "node:path";
27539
+ import { join as join31, resolve as resolve6 } from "node:path";
27187
27540
  import { spawn as spawn4 } from "node:child_process";
27188
27541
  var help = `teammy-server \u2014 the Teammy collaboration hub
27189
27542
 
@@ -27228,7 +27581,7 @@ async function runServerCli(args, version2) {
27228
27581
  confirm: { type: "boolean" },
27229
27582
  "data-dir": {
27230
27583
  type: "string",
27231
- default: process.env.TEAMMY_DATA_DIR ?? join30(homedir(), ".teammy", "server")
27584
+ default: process.env.TEAMMY_DATA_DIR ?? join31(homedir(), ".teammy", "server")
27232
27585
  }
27233
27586
  }
27234
27587
  });
@@ -27251,7 +27604,7 @@ async function runServerCli(args, version2) {
27251
27604
  options: {
27252
27605
  "data-dir": {
27253
27606
  type: "string",
27254
- default: process.env.TEAMMY_DATA_DIR ?? join30(homedir(), ".teammy", "server")
27607
+ default: process.env.TEAMMY_DATA_DIR ?? join31(homedir(), ".teammy", "server")
27255
27608
  },
27256
27609
  once: { type: "boolean" }
27257
27610
  }
@@ -27270,7 +27623,7 @@ async function runServerCli(args, version2) {
27270
27623
  member: { type: "string" },
27271
27624
  "data-dir": {
27272
27625
  type: "string",
27273
- default: process.env.TEAMMY_DATA_DIR ?? join30(homedir(), ".teammy", "server")
27626
+ default: process.env.TEAMMY_DATA_DIR ?? join31(homedir(), ".teammy", "server")
27274
27627
  }
27275
27628
  }
27276
27629
  });
@@ -27298,7 +27651,7 @@ async function runServerCli(args, version2) {
27298
27651
  port: { type: "string", default: process.env.TEAMMY_PORT ?? "4317" },
27299
27652
  "data-dir": {
27300
27653
  type: "string",
27301
- default: process.env.TEAMMY_DATA_DIR ?? join30(homedir(), ".teammy", "server")
27654
+ default: process.env.TEAMMY_DATA_DIR ?? join31(homedir(), ".teammy", "server")
27302
27655
  },
27303
27656
  "with-worker": { type: "boolean", default: false }
27304
27657
  }