dominds 1.2.5 → 1.2.7

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 (149) hide show
  1. package/dist/agent-priming.js +2051 -0
  2. package/dist/apps/app-lock-file.js +228 -0
  3. package/dist/apps/assigned-port.js +124 -0
  4. package/dist/apps/enabled-apps.js +472 -7
  5. package/dist/apps/manifest.js +37 -0
  6. package/dist/apps/override-paths.js +19 -6
  7. package/dist/apps/problems.js +43 -0
  8. package/dist/apps/resolution-file.js +370 -0
  9. package/dist/apps/runtime.js +5 -17
  10. package/dist/apps/teammates.js +102 -1
  11. package/dist/cli/disable.js +10 -6
  12. package/dist/cli/enable.js +21 -19
  13. package/dist/cli/install.js +40 -18
  14. package/dist/cli/uninstall.js +6 -6
  15. package/dist/cli/update.js +38 -13
  16. package/dist/dialog.js +5 -0
  17. package/dist/docs/app-constitution.md +85 -18
  18. package/dist/docs/app-constitution.zh.md +86 -21
  19. package/dist/docs/dialog-system.md +1 -1
  20. package/dist/docs/dialog-system.zh.md +1 -1
  21. package/dist/docs/dominds-agent-priming.md +218 -0
  22. package/dist/docs/dominds-agent-priming.zh.md +196 -0
  23. package/dist/docs/drive-logic-context-refactor-plan.zh.md +338 -0
  24. package/dist/docs/keep-going.md +176 -0
  25. package/dist/docs/keep-going.zh.md +162 -0
  26. package/dist/docs/showing-by-doing.md +208 -0
  27. package/dist/docs/showing-by-doing.zh.md +177 -0
  28. package/dist/docs/team-mgmt-toolset.md +482 -0
  29. package/dist/docs/team-mgmt-toolset.zh.md +426 -0
  30. package/dist/llm/defaults.yaml +1 -1
  31. package/dist/llm/driver.js +4093 -0
  32. package/dist/llm/kernel-driver/drive.js +5 -2
  33. package/dist/llm/kernel-driver/flow.js +3 -0
  34. package/dist/minds/promptdocs.js +263 -0
  35. package/dist/problems.js +67 -16
  36. package/dist/server/api-routes.js +333 -0
  37. package/dist/server/prompts-routes.js +545 -0
  38. package/dist/server/server-core.js +4 -0
  39. package/dist/server/websocket-handler.js +17 -0
  40. package/dist/shared/team-mgmt-manual.js +120 -0
  41. package/dist/shared/types/prompts.js +2 -0
  42. package/dist/shared/types/tellask.js +8 -0
  43. package/dist/showing-by-doing.js +1091 -0
  44. package/dist/snippets/README.en.md +3 -0
  45. package/dist/snippets/README.md +4 -0
  46. package/dist/static/assets/{_basePickBy-CF9r08iy.js → _basePickBy-BMCtwrV7.js} +3 -3
  47. package/dist/static/assets/{_basePickBy-CF9r08iy.js.map → _basePickBy-BMCtwrV7.js.map} +1 -1
  48. package/dist/static/assets/{_baseUniq-CxKv0cd4.js → _baseUniq-BuyCgJiA.js} +2 -2
  49. package/dist/static/assets/{_baseUniq-CxKv0cd4.js.map → _baseUniq-BuyCgJiA.js.map} +1 -1
  50. package/dist/static/assets/{arc-C9JyvnlB.js → arc-BDuN8lwA.js} +2 -2
  51. package/dist/static/assets/{arc-C9JyvnlB.js.map → arc-BDuN8lwA.js.map} +1 -1
  52. package/dist/static/assets/{architectureDiagram-VXUJARFQ-CpcUgjHf.js → architectureDiagram-VXUJARFQ-C-ekqGAD.js} +7 -7
  53. package/dist/static/assets/{architectureDiagram-VXUJARFQ-CpcUgjHf.js.map → architectureDiagram-VXUJARFQ-C-ekqGAD.js.map} +1 -1
  54. package/dist/static/assets/{blockDiagram-VD42YOAC-BA9vtmm7.js → blockDiagram-VD42YOAC-CgQiNuuQ.js} +7 -7
  55. package/dist/static/assets/{blockDiagram-VD42YOAC-BA9vtmm7.js.map → blockDiagram-VD42YOAC-CgQiNuuQ.js.map} +1 -1
  56. package/dist/static/assets/{c4Diagram-YG6GDRKO-D49MGNdF.js → c4Diagram-YG6GDRKO-DONC39q-.js} +3 -3
  57. package/dist/static/assets/{c4Diagram-YG6GDRKO-D49MGNdF.js.map → c4Diagram-YG6GDRKO-DONC39q-.js.map} +1 -1
  58. package/dist/static/assets/{channel-B4KzL0Kg.js → channel-CJTFwXIG.js} +2 -2
  59. package/dist/static/assets/{channel-B4KzL0Kg.js.map → channel-CJTFwXIG.js.map} +1 -1
  60. package/dist/static/assets/{chunk-4BX2VUAB-0F-1ayl0.js → chunk-4BX2VUAB-NaIy4uLJ.js} +2 -2
  61. package/dist/static/assets/{chunk-4BX2VUAB-0F-1ayl0.js.map → chunk-4BX2VUAB-NaIy4uLJ.js.map} +1 -1
  62. package/dist/static/assets/{chunk-55IACEB6-Dnl2HDTZ.js → chunk-55IACEB6-JUKI_Ayx.js} +2 -2
  63. package/dist/static/assets/{chunk-55IACEB6-Dnl2HDTZ.js.map → chunk-55IACEB6-JUKI_Ayx.js.map} +1 -1
  64. package/dist/static/assets/{chunk-B4BG7PRW-Bhx5RbkQ.js → chunk-B4BG7PRW-dIswFJDn.js} +5 -5
  65. package/dist/static/assets/{chunk-B4BG7PRW-Bhx5RbkQ.js.map → chunk-B4BG7PRW-dIswFJDn.js.map} +1 -1
  66. package/dist/static/assets/{chunk-DI55MBZ5-EYd1wL3E.js → chunk-DI55MBZ5-DU2b_N30.js} +4 -4
  67. package/dist/static/assets/{chunk-DI55MBZ5-EYd1wL3E.js.map → chunk-DI55MBZ5-DU2b_N30.js.map} +1 -1
  68. package/dist/static/assets/{chunk-FMBD7UC4-DAjkhhUU.js → chunk-FMBD7UC4-BgExcScw.js} +2 -2
  69. package/dist/static/assets/{chunk-FMBD7UC4-DAjkhhUU.js.map → chunk-FMBD7UC4-BgExcScw.js.map} +1 -1
  70. package/dist/static/assets/{chunk-QN33PNHL-CK6TY7IE.js → chunk-QN33PNHL-bitxyqh7.js} +2 -2
  71. package/dist/static/assets/{chunk-QN33PNHL-CK6TY7IE.js.map → chunk-QN33PNHL-bitxyqh7.js.map} +1 -1
  72. package/dist/static/assets/{chunk-QZHKN3VN-CketngiE.js → chunk-QZHKN3VN-Cor8u7DT.js} +2 -2
  73. package/dist/static/assets/{chunk-QZHKN3VN-CketngiE.js.map → chunk-QZHKN3VN-Cor8u7DT.js.map} +1 -1
  74. package/dist/static/assets/{chunk-TZMSLE5B-Bcuvqo45.js → chunk-TZMSLE5B-Aceoxav_.js} +2 -2
  75. package/dist/static/assets/{chunk-TZMSLE5B-Bcuvqo45.js.map → chunk-TZMSLE5B-Aceoxav_.js.map} +1 -1
  76. package/dist/static/assets/{classDiagram-2ON5EDUG-CaP4T3r4.js → classDiagram-2ON5EDUG-D1Q6a8Hg.js} +6 -6
  77. package/dist/static/assets/{classDiagram-2ON5EDUG-CaP4T3r4.js.map → classDiagram-2ON5EDUG-D1Q6a8Hg.js.map} +1 -1
  78. package/dist/static/assets/{classDiagram-v2-WZHVMYZB-CaP4T3r4.js → classDiagram-v2-WZHVMYZB-D1Q6a8Hg.js} +6 -6
  79. package/dist/static/assets/{classDiagram-v2-WZHVMYZB-CaP4T3r4.js.map → classDiagram-v2-WZHVMYZB-D1Q6a8Hg.js.map} +1 -1
  80. package/dist/static/assets/{clone-C-JULvnG.js → clone-MlWbv1V0.js} +2 -2
  81. package/dist/static/assets/{clone-C-JULvnG.js.map → clone-MlWbv1V0.js.map} +1 -1
  82. package/dist/static/assets/{cose-bilkent-S5V4N54A-vXCmi_eC.js → cose-bilkent-S5V4N54A-DWPCXSrn.js} +2 -2
  83. package/dist/static/assets/{cose-bilkent-S5V4N54A-vXCmi_eC.js.map → cose-bilkent-S5V4N54A-DWPCXSrn.js.map} +1 -1
  84. package/dist/static/assets/{dagre-6UL2VRFP-bhGzX6kO.js → dagre-6UL2VRFP-C8ptQ9V3.js} +7 -7
  85. package/dist/static/assets/{dagre-6UL2VRFP-bhGzX6kO.js.map → dagre-6UL2VRFP-C8ptQ9V3.js.map} +1 -1
  86. package/dist/static/assets/{diagram-PSM6KHXK-BUKfmfGk.js → diagram-PSM6KHXK-Bgf1FqkE.js} +8 -8
  87. package/dist/static/assets/{diagram-PSM6KHXK-BUKfmfGk.js.map → diagram-PSM6KHXK-Bgf1FqkE.js.map} +1 -1
  88. package/dist/static/assets/{diagram-QEK2KX5R-DYlq3uFq.js → diagram-QEK2KX5R-BZ5xzofU.js} +7 -7
  89. package/dist/static/assets/{diagram-QEK2KX5R-DYlq3uFq.js.map → diagram-QEK2KX5R-BZ5xzofU.js.map} +1 -1
  90. package/dist/static/assets/{diagram-S2PKOQOG-CjxkLHWG.js → diagram-S2PKOQOG-Dwp47T9I.js} +7 -7
  91. package/dist/static/assets/{diagram-S2PKOQOG-CjxkLHWG.js.map → diagram-S2PKOQOG-Dwp47T9I.js.map} +1 -1
  92. package/dist/static/assets/{erDiagram-Q2GNP2WA-S3hR85On.js → erDiagram-Q2GNP2WA-Cx4weIHl.js} +5 -5
  93. package/dist/static/assets/{erDiagram-Q2GNP2WA-S3hR85On.js.map → erDiagram-Q2GNP2WA-Cx4weIHl.js.map} +1 -1
  94. package/dist/static/assets/{flowDiagram-NV44I4VS-aBmNMuQ0.js → flowDiagram-NV44I4VS-vNUuIeRk.js} +6 -6
  95. package/dist/static/assets/{flowDiagram-NV44I4VS-aBmNMuQ0.js.map → flowDiagram-NV44I4VS-vNUuIeRk.js.map} +1 -1
  96. package/dist/static/assets/{ganttDiagram-JELNMOA3-DJxXaiW1.js → ganttDiagram-JELNMOA3-BEfozJAr.js} +3 -3
  97. package/dist/static/assets/{ganttDiagram-JELNMOA3-DJxXaiW1.js.map → ganttDiagram-JELNMOA3-BEfozJAr.js.map} +1 -1
  98. package/dist/static/assets/{gitGraphDiagram-V2S2FVAM-DEOBCM0G.js → gitGraphDiagram-V2S2FVAM-eHxwc3d9.js} +8 -8
  99. package/dist/static/assets/{gitGraphDiagram-V2S2FVAM-DEOBCM0G.js.map → gitGraphDiagram-V2S2FVAM-eHxwc3d9.js.map} +1 -1
  100. package/dist/static/assets/{graph-DwrKSIE7.js → graph-C6a6uAok.js} +3 -3
  101. package/dist/static/assets/{graph-DwrKSIE7.js.map → graph-C6a6uAok.js.map} +1 -1
  102. package/dist/static/assets/{index-HWTRvE2k.js → index-D3TQbAKh.js} +383 -59
  103. package/dist/static/assets/index-D3TQbAKh.js.map +1 -0
  104. package/dist/static/assets/{infoDiagram-HS3SLOUP-BH9kVuYd.js → infoDiagram-HS3SLOUP-CX0NiId3.js} +6 -6
  105. package/dist/static/assets/{infoDiagram-HS3SLOUP-BH9kVuYd.js.map → infoDiagram-HS3SLOUP-CX0NiId3.js.map} +1 -1
  106. package/dist/static/assets/{journeyDiagram-XKPGCS4Q-Dap7AcjR.js → journeyDiagram-XKPGCS4Q-C1IepPZ-.js} +5 -5
  107. package/dist/static/assets/{journeyDiagram-XKPGCS4Q-Dap7AcjR.js.map → journeyDiagram-XKPGCS4Q-C1IepPZ-.js.map} +1 -1
  108. package/dist/static/assets/{kanban-definition-3W4ZIXB7-4NOl8MEj.js → kanban-definition-3W4ZIXB7-uMNX4Z1W.js} +3 -3
  109. package/dist/static/assets/{kanban-definition-3W4ZIXB7-4NOl8MEj.js.map → kanban-definition-3W4ZIXB7-uMNX4Z1W.js.map} +1 -1
  110. package/dist/static/assets/{layout-D6uIxu1E.js → layout-CpE3kk5z.js} +5 -5
  111. package/dist/static/assets/{layout-D6uIxu1E.js.map → layout-CpE3kk5z.js.map} +1 -1
  112. package/dist/static/assets/{linear-CvBOGQA2.js → linear-DV8laXr9.js} +2 -2
  113. package/dist/static/assets/{linear-CvBOGQA2.js.map → linear-DV8laXr9.js.map} +1 -1
  114. package/dist/static/assets/{mindmap-definition-VGOIOE7T-ugsrLNY5.js → mindmap-definition-VGOIOE7T-CKjgVM9S.js} +4 -4
  115. package/dist/static/assets/{mindmap-definition-VGOIOE7T-ugsrLNY5.js.map → mindmap-definition-VGOIOE7T-CKjgVM9S.js.map} +1 -1
  116. package/dist/static/assets/{pieDiagram-ADFJNKIX-CdVZjM8g.js → pieDiagram-ADFJNKIX-BBonlNyT.js} +8 -8
  117. package/dist/static/assets/{pieDiagram-ADFJNKIX-CdVZjM8g.js.map → pieDiagram-ADFJNKIX-BBonlNyT.js.map} +1 -1
  118. package/dist/static/assets/{quadrantDiagram-AYHSOK5B-A6m5lZKd.js → quadrantDiagram-AYHSOK5B-BTI8HbBu.js} +3 -3
  119. package/dist/static/assets/{quadrantDiagram-AYHSOK5B-A6m5lZKd.js.map → quadrantDiagram-AYHSOK5B-BTI8HbBu.js.map} +1 -1
  120. package/dist/static/assets/{requirementDiagram-UZGBJVZJ-Cac3zSJH.js → requirementDiagram-UZGBJVZJ-ZtSr9Q5R.js} +4 -4
  121. package/dist/static/assets/{requirementDiagram-UZGBJVZJ-Cac3zSJH.js.map → requirementDiagram-UZGBJVZJ-ZtSr9Q5R.js.map} +1 -1
  122. package/dist/static/assets/{sankeyDiagram-TZEHDZUN-DXDdUUl1.js → sankeyDiagram-TZEHDZUN-DibLVGzg.js} +2 -2
  123. package/dist/static/assets/{sankeyDiagram-TZEHDZUN-DXDdUUl1.js.map → sankeyDiagram-TZEHDZUN-DibLVGzg.js.map} +1 -1
  124. package/dist/static/assets/{sequenceDiagram-WL72ISMW-Domsjl5Y.js → sequenceDiagram-WL72ISMW-qXatfzVt.js} +4 -4
  125. package/dist/static/assets/{sequenceDiagram-WL72ISMW-Domsjl5Y.js.map → sequenceDiagram-WL72ISMW-qXatfzVt.js.map} +1 -1
  126. package/dist/static/assets/{stateDiagram-FKZM4ZOC-Bu0lRQK1.js → stateDiagram-FKZM4ZOC-7fgxCQHo.js} +9 -9
  127. package/dist/static/assets/{stateDiagram-FKZM4ZOC-Bu0lRQK1.js.map → stateDiagram-FKZM4ZOC-7fgxCQHo.js.map} +1 -1
  128. package/dist/static/assets/{stateDiagram-v2-4FDKWEC3-D0K-n3ic.js → stateDiagram-v2-4FDKWEC3-DcWlOAnF.js} +5 -5
  129. package/dist/static/assets/{stateDiagram-v2-4FDKWEC3-D0K-n3ic.js.map → stateDiagram-v2-4FDKWEC3-DcWlOAnF.js.map} +1 -1
  130. package/dist/static/assets/{timeline-definition-IT6M3QCI-BGvpddwR.js → timeline-definition-IT6M3QCI-iX2MRdpY.js} +3 -3
  131. package/dist/static/assets/{timeline-definition-IT6M3QCI-BGvpddwR.js.map → timeline-definition-IT6M3QCI-iX2MRdpY.js.map} +1 -1
  132. package/dist/static/assets/{treemap-GDKQZRPO-BoOzOm2j.js → treemap-GDKQZRPO-AVRnyXu1.js} +5 -5
  133. package/dist/static/assets/{treemap-GDKQZRPO-BoOzOm2j.js.map → treemap-GDKQZRPO-AVRnyXu1.js.map} +1 -1
  134. package/dist/static/assets/{xychartDiagram-PRI3JC2R-C_h3_ICR.js → xychartDiagram-PRI3JC2R-DVYEo5aJ.js} +3 -3
  135. package/dist/static/assets/{xychartDiagram-PRI3JC2R-C_h3_ICR.js.map → xychartDiagram-PRI3JC2R-DVYEo5aJ.js.map} +1 -1
  136. package/dist/static/index.html +1 -1
  137. package/dist/team.js +52 -48
  138. package/dist/tellask.js +439 -0
  139. package/dist/tools/context-health.js +177 -0
  140. package/dist/tools/diag.js +583 -0
  141. package/dist/tools/fs.js +194 -68
  142. package/dist/tools/prompts/memory/en/principles.md +13 -5
  143. package/dist/tools/prompts/memory/en/tools.md +11 -36
  144. package/dist/tools/prompts/memory/zh/principles.md +18 -8
  145. package/dist/tools/prompts/memory/zh/tools.md +11 -36
  146. package/dist/tools/team-mgmt.js +3487 -0
  147. package/dist/utils/task-doc.js +236 -0
  148. package/package.json +1 -1
  149. package/dist/static/assets/index-HWTRvE2k.js.map +0 -1
@@ -0,0 +1,1091 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.getShowingByDoingCacheStatus = getShowingByDoingCacheStatus;
37
+ exports.scheduleShowingByDoingForNewDialog = scheduleShowingByDoingForNewDialog;
38
+ const dialog_run_state_1 = require("./dialog-run-state");
39
+ const client_1 = require("./llm/client");
40
+ const driver_1 = require("./llm/driver");
41
+ const registry_1 = require("./llm/gen/registry");
42
+ const log_1 = require("./log");
43
+ const load_1 = require("./minds/load");
44
+ const runtime_language_1 = require("./shared/runtime-language");
45
+ const id_1 = require("./shared/utils/id");
46
+ const inter_dialog_format_1 = require("./shared/utils/inter-dialog-format");
47
+ const time_1 = require("./shared/utils/time");
48
+ const team_1 = require("./team");
49
+ const BASELINE_ENV_SNAPSHOT_CMD = 'uname -a';
50
+ const cacheByTellaskerAgentId = new Map();
51
+ const inflightByTellaskerAgentId = new Map();
52
+ async function emitSayingEventsAndPersist(dlg, content) {
53
+ const calls = await (0, driver_1.emitSayingEvents)(dlg, content);
54
+ const genseq = dlg.activeGenSeqOrUndefined;
55
+ if (dlg.generationStarted &&
56
+ typeof genseq === 'number' &&
57
+ Number.isFinite(genseq) &&
58
+ genseq > 0 &&
59
+ content.trim()) {
60
+ try {
61
+ await dlg.persistAgentMessage(content, genseq, 'saying_msg');
62
+ }
63
+ catch (err) {
64
+ log_1.log.warn('Failed to persist Showing-by-Doing synthetic saying content (best-effort)', err, {
65
+ dialogId: dlg.id.valueOf(),
66
+ genseq,
67
+ });
68
+ }
69
+ }
70
+ return calls;
71
+ }
72
+ async function emitUiOnlyMarkdownEventsAndPersist(dlg, content) {
73
+ const trimmed = content.trim();
74
+ if (!trimmed)
75
+ return;
76
+ await dlg.markdownStart();
77
+ await dlg.markdownChunk(content);
78
+ await dlg.markdownFinish();
79
+ const genseq = dlg.activeGenSeqOrUndefined;
80
+ if (dlg.generationStarted &&
81
+ typeof genseq === 'number' &&
82
+ Number.isFinite(genseq) &&
83
+ genseq > 0) {
84
+ try {
85
+ await dlg.persistUiOnlyMarkdown(content, genseq);
86
+ }
87
+ catch (err) {
88
+ log_1.log.warn('Failed to persist UI-only markdown (best-effort)', err, {
89
+ dialogId: dlg.id.valueOf(),
90
+ genseq,
91
+ });
92
+ }
93
+ }
94
+ }
95
+ function parseUnifiedTimestamp(value) {
96
+ const m = value.trim().match(/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/);
97
+ if (!m)
98
+ return null;
99
+ const year = Number(m[1]);
100
+ const month = Number(m[2]);
101
+ const day = Number(m[3]);
102
+ const hour = Number(m[4]);
103
+ const minute = Number(m[5]);
104
+ const second = Number(m[6]);
105
+ if (!Number.isFinite(year) ||
106
+ !Number.isFinite(month) ||
107
+ !Number.isFinite(day) ||
108
+ !Number.isFinite(hour) ||
109
+ !Number.isFinite(minute) ||
110
+ !Number.isFinite(second)) {
111
+ return null;
112
+ }
113
+ return new Date(year, month - 1, day, hour, minute, second);
114
+ }
115
+ function getShowingByDoingCacheStatus(agentId) {
116
+ const entry = cacheByTellaskerAgentId.get(agentId);
117
+ if (!entry)
118
+ return { hasCache: false };
119
+ const createdAt = entry.createdAt;
120
+ const parsed = parseUnifiedTimestamp(createdAt);
121
+ const ageSeconds = parsed === null ? 0 : Math.max(0, Math.floor((Date.now() - parsed.getTime()) / 1000));
122
+ return { hasCache: true, createdAt, ageSeconds };
123
+ }
124
+ function scheduleShowingByDoingForNewDialog(dlg, options) {
125
+ if (options.mode === 'skip')
126
+ return;
127
+ const tellaskerAgentId = dlg.agentId;
128
+ const existing = cacheByTellaskerAgentId.get(tellaskerAgentId);
129
+ if (options.mode === 'reuse' && existing) {
130
+ dlg.setCoursePrefixMsgs(buildCoursePrefixMsgs(existing));
131
+ void replayShowingByDoing(dlg, existing);
132
+ return;
133
+ }
134
+ const inflight = inflightByTellaskerAgentId.get(tellaskerAgentId);
135
+ if (inflight) {
136
+ void inflight.then((entry) => {
137
+ if (options.mode === 'reuse') {
138
+ dlg.setCoursePrefixMsgs(buildCoursePrefixMsgs(entry));
139
+ return replayShowingByDoing(dlg, entry);
140
+ }
141
+ // mode === 'do': wait for in-flight then run again for this dialog.
142
+ return runShowingByDoingLive(dlg).then((next) => {
143
+ cacheByTellaskerAgentId.set(tellaskerAgentId, next);
144
+ });
145
+ });
146
+ return;
147
+ }
148
+ const task = runShowingByDoingLive(dlg)
149
+ .then((entry) => {
150
+ cacheByTellaskerAgentId.set(tellaskerAgentId, entry);
151
+ return entry;
152
+ })
153
+ .catch((err) => {
154
+ log_1.log.warn('Showing-by-Doing live run failed; will retry on next dialog', err, {
155
+ agentId: tellaskerAgentId,
156
+ });
157
+ throw err;
158
+ })
159
+ .finally(() => {
160
+ inflightByTellaskerAgentId.delete(tellaskerAgentId);
161
+ });
162
+ inflightByTellaskerAgentId.set(tellaskerAgentId, task);
163
+ void task;
164
+ }
165
+ function prefixTellaskBodyLines(text) {
166
+ const lines = text.replace(/\r\n/g, '\n').split('\n');
167
+ return lines.map((line) => `!? ${line}`).join('\n');
168
+ }
169
+ function takeFirstNonEmptyLine(text) {
170
+ const lines = text.replace(/\r\n/g, '\n').split('\n');
171
+ for (const line of lines) {
172
+ const trimmed = line.trim();
173
+ if (trimmed)
174
+ return trimmed;
175
+ }
176
+ return null;
177
+ }
178
+ function extractLastAssistantSaying(messages) {
179
+ for (let i = messages.length - 1; i >= 0; i--) {
180
+ const msg = messages[i];
181
+ if (msg.type === 'saying_msg' && typeof msg.content === 'string' && msg.content.trim()) {
182
+ return msg.content;
183
+ }
184
+ }
185
+ for (let i = messages.length - 1; i >= 0; i--) {
186
+ const msg = messages[i];
187
+ if (msg.type === 'thinking_msg' && typeof msg.content === 'string' && msg.content.trim()) {
188
+ return msg.content;
189
+ }
190
+ }
191
+ return '';
192
+ }
193
+ function extractLastShellCmdResultText(messages) {
194
+ for (let i = messages.length - 1; i >= 0; i--) {
195
+ const msg = messages[i];
196
+ if (typeof msg !== 'object' || msg === null)
197
+ continue;
198
+ if (!('type' in msg) || !('name' in msg) || !('content' in msg))
199
+ continue;
200
+ const type = msg.type;
201
+ const name = msg.name;
202
+ const content = msg.content;
203
+ if (type !== 'func_result_msg')
204
+ continue;
205
+ if (name !== 'shell_cmd')
206
+ continue;
207
+ if (typeof content !== 'string')
208
+ continue;
209
+ if (!content.trim())
210
+ continue;
211
+ return content;
212
+ }
213
+ return null;
214
+ }
215
+ function shuffleCopy(items) {
216
+ const out = items.slice();
217
+ for (let i = out.length - 1; i >= 1; i--) {
218
+ const j = Math.floor(Math.random() * (i + 1));
219
+ const tmp = out[i];
220
+ out[i] = out[j];
221
+ out[j] = tmp;
222
+ }
223
+ return out;
224
+ }
225
+ async function runUnameA() {
226
+ const { spawn } = await Promise.resolve().then(() => __importStar(require('child_process')));
227
+ return await new Promise((resolveUname) => {
228
+ const child = spawn('uname', ['-a'], { stdio: ['ignore', 'pipe', 'pipe'] });
229
+ let out = '';
230
+ let err = '';
231
+ child.stdout.on('data', (buf) => {
232
+ out += buf.toString();
233
+ });
234
+ child.stderr.on('data', (buf) => {
235
+ err += buf.toString();
236
+ });
237
+ child.on('close', (code) => {
238
+ const trimmedOut = out.trim();
239
+ const trimmedErr = err.trim();
240
+ if (code === 0 && trimmedOut) {
241
+ resolveUname(trimmedOut);
242
+ return;
243
+ }
244
+ const fallback = trimmedErr ? trimmedErr : `uname exited with code ${String(code)}`;
245
+ resolveUname(fallback);
246
+ });
247
+ child.on('error', (e) => {
248
+ resolveUname(e instanceof Error ? e.message : String(e));
249
+ });
250
+ });
251
+ }
252
+ function formatPreludeIntro(language, reused, shellPolicy) {
253
+ const shellPolicyLinesZh = shellPolicy === 'specialist_only'
254
+ ? [
255
+ '规则:此智能体**不执行任何 shell 命令**。所有 shell 命令必须通过 `shell_specialist` 执行并回传。',
256
+ '下面将诉请 shell 专员仅执行一个低风险命令:`uname -a`。',
257
+ ]
258
+ : shellPolicy === 'self_is_specialist'
259
+ ? [
260
+ '本次对话主理人属于 `shell_specialists`,将略去 shell 诉请环节。',
261
+ '由 Dominds 运行时执行一个基线命令:`uname -a`,随后进入 `!?@self` FBR。',
262
+ ]
263
+ : [
264
+ '本团队未配置 `shell_specialist`。',
265
+ '规则:此智能体必须**不执行任何 shell 命令**(不能“自己跑一下看看”)。',
266
+ '后续只能通过文件读写等非 shell 工具推进;同时要结合环境快照留意系统相关注意事项。',
267
+ '由 Dominds 运行时仅执行一个基线命令:`uname -a`,随后进入 `!?@self` FBR。',
268
+ ];
269
+ const shellPolicyLinesEn = shellPolicy === 'specialist_only'
270
+ ? [
271
+ 'Rule: this agent must **not run any shell commands**. All shell commands must be executed by a `shell_specialist` and returned.',
272
+ 'Next, we Tellask the shell specialist to run one low-risk command only: `uname -a`.',
273
+ ]
274
+ : shellPolicy === 'self_is_specialist'
275
+ ? [
276
+ 'The dialog owner is a member of `shell_specialists`, so we skip the shell Tellask step.',
277
+ 'Dominds runtime runs one baseline command: `uname -a`, then we enter `!?@self` FBR.',
278
+ ]
279
+ : [
280
+ 'This team has no configured `shell_specialist`.',
281
+ 'Rule: this agent must **not run any shell commands** (no “just try it locally”).',
282
+ 'We can only proceed with non-shell tools like file read/write; still, we must watch out for environment-specific constraints.',
283
+ 'Dominds runtime runs one baseline command only: `uname -a`, then we enter `!?@self` FBR.',
284
+ ];
285
+ if (language === 'zh') {
286
+ return reused
287
+ ? [
288
+ '## Prelude:智能体启动(复用缓存)',
289
+ '',
290
+ '这段序幕用于把“诉请 + 回传 + FBR + 综合提炼”变成体感(引导祂做给自己看)。',
291
+ '本次对话复用了本进程内缓存:未重复执行命令。',
292
+ '',
293
+ ...shellPolicyLinesZh,
294
+ '',
295
+ ].join('\n')
296
+ : [
297
+ '## Prelude:智能体启动',
298
+ '',
299
+ '这段序幕用于把“诉请 + 回传 + FBR + 综合提炼”变成体感(引导祂做给自己看)。',
300
+ '',
301
+ ...shellPolicyLinesZh,
302
+ '',
303
+ ].join('\n');
304
+ }
305
+ return reused
306
+ ? [
307
+ '## Prelude: Agent Priming (Reused)',
308
+ '',
309
+ 'This prelude makes Tellask + return + FBR + synthesis feel real (guiding the agent to show it to itself).',
310
+ 'This dialog reused the in-process cache (no commands were re-run).',
311
+ '',
312
+ ...shellPolicyLinesEn,
313
+ '',
314
+ ].join('\n')
315
+ : [
316
+ '## Prelude: Agent Priming',
317
+ '',
318
+ 'This prelude makes Tellask + return + FBR + synthesis feel real (guiding the agent to show it to itself).',
319
+ '',
320
+ ...shellPolicyLinesEn,
321
+ '',
322
+ ].join('\n');
323
+ }
324
+ function formatShellTellaskBody(language) {
325
+ if (language === 'zh') {
326
+ return [
327
+ '你是 shell 专员:请代我执行 `uname -a` 获取当前运行环境的基本信息。',
328
+ '',
329
+ '背景规则:对话主理人不得执行任何 shell 命令;所有 shell 命令必须通过你执行并回传。',
330
+ '请不要建议我“自己在本地跑一下”。',
331
+ '',
332
+ '要求:',
333
+ '- 通过 shell 工具执行:uname -a(只执行这一条)',
334
+ '- 原样返回输出(不要改写/解释)',
335
+ '- 若命令不可用/失败:返回错误信息,并给出一个安全的替代命令',
336
+ '',
337
+ '输出格式:优先只给出原始输出,其次才是必要的简短说明。',
338
+ ].join('\n');
339
+ }
340
+ return [
341
+ 'You are the shell specialist: please run `uname -a` on my behalf to capture the basic runtime environment.',
342
+ '',
343
+ 'Rule: the dialog owner must not run any shell commands; all shell commands must be executed by you and returned.',
344
+ 'Do not suggest that I “just run it locally”.',
345
+ '',
346
+ 'Requirements:',
347
+ '- Use shell tools to run exactly: uname -a (and only this command)',
348
+ '- Return the raw output verbatim (no paraphrase)',
349
+ '- If the command fails: include the error and suggest one safe alternative command',
350
+ '',
351
+ 'Output format: prefer raw output only; keep any explanation minimal.',
352
+ ].join('\n');
353
+ }
354
+ function formatFbrTellaskBody(language, snapshotCmd, snapshotText, shellPolicy, options) {
355
+ const shellPolicyTailZh = shellPolicy === 'specialist_only'
356
+ ? [
357
+ '',
358
+ '约束提醒:后续如需任何 shell 命令,必须诉请 `shell_specialist` 执行并回传;此智能体不应自行执行。',
359
+ ].join('\n')
360
+ : shellPolicy === 'no_specialist'
361
+ ? [
362
+ '',
363
+ '约束提醒:本团队无 `shell_specialist`,因此后续**不能执行任意 shell 命令**;只能通过文件读写等非 shell 工具推进。',
364
+ ].join('\n')
365
+ : '';
366
+ const shellPolicyTailEn = shellPolicy === 'specialist_only'
367
+ ? [
368
+ '',
369
+ 'Constraint: if we need any shell command later, we must Tellask a `shell_specialist` to run it and return; this agent must not run it directly.',
370
+ ].join('\n')
371
+ : shellPolicy === 'no_specialist'
372
+ ? [
373
+ '',
374
+ 'Constraint: this team has no `shell_specialist`, so we must **not run arbitrary shell commands**; proceed only with non-shell tools like file read/write.',
375
+ ].join('\n')
376
+ : '';
377
+ const fbrEffort = Math.max(0, Math.floor(options.fbrEffort));
378
+ const effortLineZh = fbrEffort >= 1
379
+ ? `运行时提示:本次 FBR 的努力倍数为 ${fbrEffort}(fbr-effort=${fbrEffort})。运行时会生成多份“初心自我”独立推理草稿,供上游对话综合提炼(这些草稿之间没有稳定映射关系,不要把它们当作固定身份)。请给出你这一份独立分析。`
380
+ : '运行时提示:本成员已禁用 FBR(fbr-effort=0)。';
381
+ const effortLineEn = fbrEffort >= 1
382
+ ? `Runtime note: FBR effort multiplier is ${fbrEffort} (fbr-effort=${fbrEffort}). The runtime will generate multiple independent “fresh boots” drafts for the upstream dialog to synthesize (no stable mapping—do not treat them as fixed identities). Please produce your own independent analysis.`
383
+ : 'Runtime note: FBR is disabled for this member (fbr-effort=0).';
384
+ const askBackHintZh = (() => {
385
+ if (shellPolicy === 'specialist_only') {
386
+ return [
387
+ '提示:如果你还想知道更多系统细节(`uname -a` 之外),可在本 FBR 支线对话中用 `!?@tellasker` 回问诉请者(上游对话)。',
388
+ '诉请者可据此选择不违反安全协议的命令,并交由 `shell_specialist` 执行回传。',
389
+ '(当前这次 FBR 请不要真的发起任何诉请;只需说明你会回问什么。)',
390
+ ].join('\n');
391
+ }
392
+ if (shellPolicy === 'no_specialist') {
393
+ return [
394
+ '提示:如果你还想知道更多系统细节(`uname -a` 之外),可在本 FBR 支线对话中用 `!?@tellasker` 回问诉请者(上游对话)补充信息。',
395
+ '注意:本团队无 `shell_specialist`,因此仍然**不得执行任意 shell 命令**;只能请求补充文本材料(文件片段/日志/配置/运行报错等)。',
396
+ '(当前这次 FBR 请不要真的发起任何诉请;只需说明你会回问什么。)',
397
+ ].join('\n');
398
+ }
399
+ return [
400
+ '提示:如果你还想知道更多系统细节(`uname -a` 之外),可在本 FBR 支线对话中用 `!?@tellasker` 回问诉请者(上游对话)。',
401
+ '(当前这次 FBR 请不要真的发起任何诉请;只需说明你会回问什么。)',
402
+ ].join('\n');
403
+ })();
404
+ const askBackHintEn = (() => {
405
+ if (shellPolicy === 'specialist_only') {
406
+ return [
407
+ 'Hint: if you want more system details beyond `uname -a`, ask back in this FBR sideline dialog via `!?@tellasker` (to the upstream tellasker dialog).',
408
+ 'Then the tellasker can choose safety-compliant follow-up commands and have a `shell_specialist` run and return them.',
409
+ '(In this FBR run, do not actually emit any tellasks; just state what you would ask back.)',
410
+ ].join('\n');
411
+ }
412
+ if (shellPolicy === 'no_specialist') {
413
+ return [
414
+ 'Hint: if you want more system details beyond `uname -a`, ask back in this FBR sideline dialog via `!?@tellasker` (to the upstream tellasker dialog).',
415
+ 'Note: there is no `shell_specialist` in this team, so do **not** run arbitrary shell commands; request additional text materials only (file snippets/logs/configs/errors).',
416
+ '(In this FBR run, do not actually emit any tellasks; just state what you would ask back.)',
417
+ ].join('\n');
418
+ }
419
+ return [
420
+ 'Hint: if you want more system details beyond `uname -a`, ask back in this FBR sideline dialog via `!?@tellasker` (to the upstream tellasker dialog).',
421
+ '(In this FBR run, do not actually emit any tellasks; just state what you would ask back.)',
422
+ ].join('\n');
423
+ })();
424
+ if (language === 'zh') {
425
+ return [
426
+ '你正在进行一次“扪心自问”(FBR)。你**没有任何工具**:不能调用工具,只能使用本文本推理。',
427
+ effortLineZh,
428
+ '',
429
+ askBackHintZh,
430
+ '',
431
+ '请基于下面环境信息回答:',
432
+ '- 在这个环境里要注意些什么?',
433
+ '- 优先利用哪些命令行工具,为什么?',
434
+ '',
435
+ `环境信息(当前 Dominds 运行时真实环境快照;来自命令:\`${snapshotCmd}\`):`,
436
+ snapshotText,
437
+ shellPolicyTailZh,
438
+ ].join('\n');
439
+ }
440
+ return [
441
+ 'You are doing Fresh Boots Reasoning (FBR). You have **no tools**: do not call tools; reason with text only.',
442
+ effortLineEn,
443
+ '',
444
+ askBackHintEn,
445
+ '',
446
+ 'Based on the environment info below, answer:',
447
+ '- What should we watch out for in this environment?',
448
+ '- Which CLI tools should we prioritize, and why?',
449
+ '',
450
+ `Environment info (a real snapshot of the current Dominds runtime; from \`${snapshotCmd}\`):`,
451
+ snapshotText,
452
+ shellPolicyTailEn,
453
+ ].join('\n');
454
+ }
455
+ function formatPrimingNoteFallback(language, unameLine, shellPolicy) {
456
+ const header = language === 'zh' ? '## 智能体启动(Agent Priming)' : '## Agent Priming';
457
+ const policyNote = shellPolicy === 'specialist_only'
458
+ ? language === 'zh'
459
+ ? '规则:所有 shell 命令必须通过 `shell_specialist` 执行并回传。'
460
+ : 'Rule: all shell commands must be executed by a `shell_specialist` and returned.'
461
+ : shellPolicy === 'no_specialist'
462
+ ? language === 'zh'
463
+ ? '规则:无 `shell_specialist`;后续不得执行任意 shell 命令,只能用文件读写等非 shell 工具。'
464
+ : 'Rule: no `shell_specialist`; do not run arbitrary shell commands—use non-shell tools like file read/write.'
465
+ : '';
466
+ const unameSectionLabel = language === 'zh' ? '`uname -a`(摘要)' : '`uname -a` (summary)';
467
+ const unameBlock = unameLine
468
+ ? ['```console', unameLine, '```'].join('\n')
469
+ : language === 'zh'
470
+ ? '_(未能提取单行摘要;详见上文输出)_'
471
+ : '_(Failed to extract a single-line summary; see output above.)_';
472
+ return [
473
+ header,
474
+ '',
475
+ policyNote ? `${policyNote}\n` : '',
476
+ `${unameSectionLabel}:`,
477
+ unameBlock,
478
+ '',
479
+ language === 'zh'
480
+ ? '(综合提炼未生成;请参考上文 FBR 草稿并自行综合。)'
481
+ : '(Synthesis unavailable; please refer to the FBR drafts above and synthesize manually.)',
482
+ ].join('\n');
483
+ }
484
+ function truncateLines(text, maxLines, maxChars) {
485
+ const normalized = text.replace(/\r\n/g, '\n');
486
+ const lines = normalized.split('\n');
487
+ const slice = lines.slice(0, Math.max(1, maxLines)).join('\n');
488
+ if (slice.length <= maxChars)
489
+ return slice;
490
+ return slice.slice(0, Math.max(0, maxChars)).trimEnd();
491
+ }
492
+ function formatPrimingSynthesisPrompt(options) {
493
+ const { language, snapshotCmd, snapshotText, fbrEffort, fbrDrafts, shellPolicy } = options;
494
+ const normalizedEffort = Math.max(0, Math.floor(fbrEffort));
495
+ const drafts = shuffleCopy([...fbrDrafts])
496
+ .map((d) => truncateLines(d, 80, 8000))
497
+ .filter((d) => d.trim() !== '');
498
+ const snapshotBlock = snapshotText.trim();
499
+ const draftsBlock = drafts.length < 1
500
+ ? language === 'zh'
501
+ ? '(无 FBR 草稿;可能是 fbr-effort=0 或生成失败。)'
502
+ : '(No FBR drafts; likely fbr-effort=0 or generation failed.)'
503
+ : drafts.join('\n\n---\n\n');
504
+ const policyLineZh = shellPolicy === 'specialist_only'
505
+ ? '约束:此智能体**不执行任何 shell 命令**;所有 shell 命令必须诉请 `shell_specialist` 执行并回传。'
506
+ : shellPolicy === 'no_specialist'
507
+ ? '约束:本团队无 `shell_specialist`,因此后续**不能执行任意 shell 命令**;只能通过文件读写等非 shell 工具推进。'
508
+ : '约束:本次对话主理人属于 `shell_specialists`,后续 shell 相关操作仍需遵循安全协议与最小风险原则。';
509
+ const policyLineEn = shellPolicy === 'specialist_only'
510
+ ? 'Constraint: this agent must **not run any shell commands**; all shell commands must be executed by a `shell_specialist` and returned.'
511
+ : shellPolicy === 'no_specialist'
512
+ ? 'Constraint: there is no `shell_specialist` in this team, so we must **not run arbitrary shell commands**; proceed only with non-shell tools like file read/write.'
513
+ : 'Constraint: the dialog owner is a member of `shell_specialists`; any shell work must still follow the safety protocol and minimize risk.';
514
+ if (language === 'zh') {
515
+ return [
516
+ '请你作为主线对话主理人,基于下面材料,生成一条短而可复用的“智能体启动(Agent Priming)”笔记。',
517
+ '要求:',
518
+ '- 使用 Markdown;以 `## 智能体启动(Agent Priming)` 开头。',
519
+ '- 明确提及本次环境快照来自命令:`' + snapshotCmd + '`(未来可能更换命令,不能靠猜)。',
520
+ '- 引导理解:这就是当前 Dominds 的**真实运行环境**,不是“某台机器”的抽象例子。',
521
+ '- 强调 shell 策略约束(见下);不要暗示“自己在本地跑一下”。',
522
+ '- “综合提炼”:从多份 FBR 草稿中取精华、去糟粕,去重/消冲突,避免逐条复述每份草稿。',
523
+ '- 不要使用序号/编号列表(顺序不重要);可用少量无序 bullet。',
524
+ '- 不要在行首输出 `!?@...`(避免被解析为真实诉请)。如果必须提及语法,请放在行内反引号里。',
525
+ '',
526
+ policyLineZh,
527
+ '',
528
+ `环境快照(来自 \`${snapshotCmd}\`):`,
529
+ snapshotBlock,
530
+ '',
531
+ `FBR 草稿(努力倍数=fbr-effort=${normalizedEffort};草稿匿名且无稳定映射关系):`,
532
+ draftsBlock,
533
+ ].join('\n');
534
+ }
535
+ return [
536
+ 'As the mainline dialog owner, use the materials below to generate a short, reusable “Agent Priming” note.',
537
+ 'Requirements:',
538
+ '- Markdown; start with `## Agent Priming`.',
539
+ '- Explicitly mention the snapshot command: `' +
540
+ snapshotCmd +
541
+ '` (do not rely on “obviousness”; the command may change).',
542
+ '- Treat this as the **real Dominds runtime environment**, not a hypothetical “some machine”.',
543
+ '- Emphasize the shell policy constraint (below); do not suggest “just run it locally”.',
544
+ '- Synthesize: extract the best from multiple FBR drafts (dedupe, reconcile conflicts) instead of repeating each draft.',
545
+ '- Avoid numbered lists (order does not matter); keep it short with a few unordered bullets.',
546
+ '- Do not output `!?@...` at the start of a line (avoid being parsed as a real Tellask). If you must mention the syntax, keep it inline in backticks.',
547
+ '',
548
+ policyLineEn,
549
+ '',
550
+ `Environment snapshot (from \`${snapshotCmd}\`):`,
551
+ snapshotBlock,
552
+ '',
553
+ `FBR drafts (effort multiplier / fbr-effort=${normalizedEffort}; anonymous with no stable mapping):`,
554
+ draftsBlock,
555
+ ].join('\n');
556
+ }
557
+ async function generatePrimingNoteViaMainlineAgent(options) {
558
+ const { dlg, snapshotCmd, snapshotText, fbrResponses, shellPolicy, fbrEffort } = options;
559
+ const language = (0, runtime_language_1.getWorkLanguage)();
560
+ try {
561
+ const minds = await (0, load_1.loadAgentMinds)(dlg.agentId, dlg);
562
+ const team = minds.team;
563
+ const agent = minds.agent;
564
+ const systemPrompt = minds.systemPrompt;
565
+ const provider = agent.provider ?? team.memberDefaults.provider;
566
+ const model = agent.model ?? team.memberDefaults.model;
567
+ if (!provider || !model) {
568
+ throw new Error(`Missing provider/model for agent '${dlg.agentId}'`);
569
+ }
570
+ const llmCfg = await client_1.LlmConfig.load();
571
+ const providerCfg = llmCfg.getProvider(provider);
572
+ if (!providerCfg) {
573
+ throw new Error(`Provider configuration not found: '${provider}'`);
574
+ }
575
+ const llmGen = (0, registry_1.getLlmGenerator)(providerCfg.apiType);
576
+ if (!llmGen) {
577
+ throw new Error(`LLM generator not found for apiType='${providerCfg.apiType}'`);
578
+ }
579
+ // Force non-streaming for this synthetic summary generation.
580
+ const agentForGen = Object.create(agent);
581
+ agentForGen.streaming = false;
582
+ // Intentionally pass zero tools: we want a pure text synthesis and must avoid accidental
583
+ // `clear_mind` / `change_mind` calls during dialog creation.
584
+ const prompt = formatPrimingSynthesisPrompt({
585
+ language,
586
+ snapshotCmd,
587
+ snapshotText,
588
+ fbrEffort,
589
+ fbrDrafts: fbrResponses,
590
+ shellPolicy,
591
+ });
592
+ const ctxMsgs = [{ type: 'environment_msg', role: 'user', content: prompt }];
593
+ const result = await llmGen.genMoreMessages(providerCfg, agentForGen, systemPrompt, [], ctxMsgs, dlg.activeGenSeq, undefined);
594
+ const saying = result.messages
595
+ .filter((m) => m.type === 'saying_msg')
596
+ .map((m) => m.content)
597
+ .join('\n')
598
+ .trim();
599
+ if (saying)
600
+ return saying;
601
+ }
602
+ catch (err) {
603
+ log_1.log.warn('Failed to generate Agent Priming note via mainline agent (best-effort)', err, {
604
+ dialogId: dlg.id.valueOf(),
605
+ });
606
+ }
607
+ const unameLine = takeFirstNonEmptyLine(snapshotText);
608
+ return formatPrimingNoteFallback(language, unameLine, shellPolicy);
609
+ }
610
+ function buildCoursePrefixMsgs(entry) {
611
+ const language = entry.workLanguage;
612
+ const header = (() => {
613
+ if (language === 'zh') {
614
+ if (entry.shellPolicy === 'specialist_only') {
615
+ return '智能体启动(Agent Priming)上下文:本进程在对话创建时已真实跑通一次“诉请(shell 专员)+ 回传 + `!?@self` FBR + 综合提炼”。以下为压缩转录,作为每一程对话的开头上下文注入。';
616
+ }
617
+ if (entry.shellPolicy === 'no_specialist') {
618
+ return '智能体启动(Agent Priming)上下文:本进程在对话创建时已获取环境快照并完成一次 `!?@self` FBR + 综合提炼(无 shell 专员;不得执行任意 shell 命令)。以下为压缩转录,作为每一程对话的开头上下文注入。';
619
+ }
620
+ return '智能体启动(Agent Priming)上下文:本进程在对话创建时已获取环境快照并完成一次 `!?@self` FBR + 综合提炼。以下为压缩转录,作为每一程对话的开头上下文注入。';
621
+ }
622
+ if (entry.shellPolicy === 'specialist_only') {
623
+ return 'Agent Priming context: this process already ran a real Tellask (shell staff) + return + `!?@self` FBR + synthesis at dialog creation. The condensed transcript below is injected at the start of each course.';
624
+ }
625
+ if (entry.shellPolicy === 'no_specialist') {
626
+ return 'Agent Priming context: this process captured an environment snapshot and ran `!?@self` FBR + synthesis at dialog creation (no shell staff; do not run arbitrary shell commands). The condensed transcript below is injected at the start of each course.';
627
+ }
628
+ return 'Agent Priming context: this process captured an environment snapshot and ran `!?@self` FBR + synthesis at dialog creation. The condensed transcript below is injected at the start of each course.';
629
+ })();
630
+ const shellSnapshotLabel = language === 'zh'
631
+ ? 'Shell 环境快照(当前 Dominds 运行时;来自 `uname -a`)'
632
+ : 'Shell environment snapshot (current Dominds runtime; `uname -a`)';
633
+ const shellSnapshot = entry.shell.snapshotText.trim()
634
+ ? entry.shell.snapshotText.trim()
635
+ : language === 'zh'
636
+ ? '(无)'
637
+ : '(empty)';
638
+ const effort = Math.max(0, Math.floor(entry.fbr.effort));
639
+ const fbrLabel = language === 'zh'
640
+ ? `FBR 输出(摘要;努力倍数=${effort},fbr-effort=${effort})`
641
+ : `FBR outputs (summary; effort×${effort}, fbr-effort=${effort})`;
642
+ const previewCap = Math.max(1, effort);
643
+ const shuffledResponses = shuffleCopy(entry.fbr.responses);
644
+ const previewResponses = shuffledResponses.slice(0, previewCap);
645
+ const blocks = [];
646
+ for (let i = 0; i < previewResponses.length; i++) {
647
+ const raw = previewResponses[i] ?? '';
648
+ const lines = raw.replace(/\r\n/g, '\n').split('\n');
649
+ const preview = lines.slice(0, 12).join('\n').trim();
650
+ blocks.push(preview ? preview : language === 'zh' ? '(无)' : '(empty)');
651
+ }
652
+ const fbrPreview = previewResponses.length < 1
653
+ ? language === 'zh'
654
+ ? '(已跳过:fbr-effort=0)'
655
+ : '(skipped: fbr-effort=0)'
656
+ : blocks.join('\n\n---\n\n');
657
+ const priming = entry.primingNote.trim();
658
+ const out = [
659
+ { type: 'transient_guide_msg', role: 'assistant', content: header },
660
+ {
661
+ type: 'environment_msg',
662
+ role: 'user',
663
+ content: `${shellSnapshotLabel}:\n\n${shellSnapshot}`,
664
+ },
665
+ {
666
+ type: 'transient_guide_msg',
667
+ role: 'assistant',
668
+ content: language === 'zh'
669
+ ? `${fbrLabel}:\n\n说明:以下为多份独立初心推理草稿(努力倍数=fbr-effort=${effort})。可能重复/冲突;主线对话应综合提炼,取各自精华、去各自糟粕,避免逐条复述。\n\n${fbrPreview}`
670
+ : `${fbrLabel}:\n\nNote: below are multiple independent FBR drafts (effort multiplier / fbr-effort=${effort}). They may overlap or conflict; the mainline dialog should synthesize (dedupe, reconcile, and extract the best), rather than repeating each draft.\n\n${fbrPreview}`,
671
+ },
672
+ ];
673
+ if (priming) {
674
+ out.push({ type: 'environment_msg', role: 'user', content: priming });
675
+ }
676
+ return out;
677
+ }
678
+ async function replayShowingByDoing(dlg, entry) {
679
+ const release = await dlg.acquire();
680
+ try {
681
+ const language = (0, runtime_language_1.getWorkLanguage)();
682
+ dlg.setCoursePrefixMsgs(buildCoursePrefixMsgs(entry));
683
+ await (0, dialog_run_state_1.setDialogRunState)(dlg.id, { kind: 'proceeding' });
684
+ // Phase 1: shell ask (and optional prelude intro)
685
+ let shellCallId = null;
686
+ let shellTellaskHead = null;
687
+ try {
688
+ await dlg.notifyGeneratingStart();
689
+ await emitUiOnlyMarkdownEventsAndPersist(dlg, formatPreludeIntro(language, true, entry.shellPolicy));
690
+ if (entry.shell.kind === 'specialist_tellask') {
691
+ const shellCallContent = [
692
+ `!?@${entry.shell.specialistId}`,
693
+ ...prefixTellaskBodyLines(entry.shell.tellaskBody).split('\n'),
694
+ '',
695
+ ].join('\n');
696
+ const shellCalls = await emitSayingEventsAndPersist(dlg, shellCallContent);
697
+ const shellCall = shellCalls.find((c) => c.validation.kind === 'valid');
698
+ if (shellCall) {
699
+ shellCallId = shellCall.callId;
700
+ shellTellaskHead = shellCall.tellaskHead;
701
+ }
702
+ }
703
+ else {
704
+ await emitSayingEventsAndPersist(dlg, entry.shell.directNoteMarkdown);
705
+ }
706
+ }
707
+ finally {
708
+ try {
709
+ await dlg.notifyGeneratingFinish();
710
+ }
711
+ catch (_finishErr) {
712
+ // best-effort
713
+ }
714
+ }
715
+ // Phase 2: shell response (separate bubble)
716
+ if (entry.shell.kind === 'specialist_tellask' && shellCallId && shellTellaskHead) {
717
+ await dlg.receiveTeammateResponse(entry.shell.specialistId, shellTellaskHead, 'completed', undefined, {
718
+ response: entry.shell.responseText,
719
+ agentId: entry.shell.specialistId,
720
+ callId: shellCallId,
721
+ originMemberId: dlg.agentId,
722
+ });
723
+ }
724
+ // Phase 3: FBR ask (call bubble)
725
+ let fbrCallId = null;
726
+ let fbrTellaskHead = null;
727
+ const effort = Math.max(0, Math.floor(entry.fbr.effort));
728
+ if (effort >= 1 && entry.fbr.responses.length > 0) {
729
+ try {
730
+ await dlg.notifyGeneratingStart();
731
+ const fbrCallContent = [
732
+ '!?@self',
733
+ ...prefixTellaskBodyLines(entry.fbr.tellaskBody).split('\n'),
734
+ '',
735
+ ].join('\n');
736
+ const fbrCalls = await emitSayingEventsAndPersist(dlg, fbrCallContent);
737
+ const fbrCall = fbrCalls.find((c) => c.validation.kind === 'valid');
738
+ if (fbrCall) {
739
+ fbrCallId = fbrCall.callId;
740
+ fbrTellaskHead = fbrCall.tellaskHead;
741
+ }
742
+ }
743
+ finally {
744
+ try {
745
+ await dlg.notifyGeneratingFinish();
746
+ }
747
+ catch (_finishErr) {
748
+ // best-effort
749
+ }
750
+ }
751
+ // Phase 4: FBR responses (separate bubbles, in stable index order)
752
+ if (fbrCallId && fbrTellaskHead) {
753
+ const normalized = Math.max(1, effort);
754
+ const responses = shuffleCopy(entry.fbr.responses).slice(0, normalized);
755
+ for (let i = 0; i < responses.length; i++) {
756
+ const raw = responses[i] ?? '';
757
+ await dlg.receiveTeammateResponse(entry.fbr.responderAgentId, fbrTellaskHead, 'completed', undefined, {
758
+ response: raw,
759
+ agentId: entry.fbr.responderAgentId,
760
+ callId: fbrCallId,
761
+ originMemberId: dlg.agentId,
762
+ });
763
+ }
764
+ }
765
+ }
766
+ // Phase 5: summary bubble
767
+ try {
768
+ await dlg.notifyGeneratingStart();
769
+ await emitSayingEventsAndPersist(dlg, entry.primingNote);
770
+ }
771
+ finally {
772
+ try {
773
+ await dlg.notifyGeneratingFinish();
774
+ }
775
+ catch (_finishErr) {
776
+ // best-effort
777
+ }
778
+ }
779
+ }
780
+ catch (err) {
781
+ log_1.log.warn('Showing-by-Doing replay failed (best-effort)', err, { dialogId: dlg.id.valueOf() });
782
+ }
783
+ finally {
784
+ let nextIdle = { kind: 'idle_waiting_user' };
785
+ try {
786
+ nextIdle = await (0, dialog_run_state_1.computeIdleRunState)(dlg);
787
+ }
788
+ catch (err) {
789
+ log_1.log.warn('Failed to compute idle runState after Showing-by-Doing replay; falling back', err, {
790
+ dialogId: dlg.id.valueOf(),
791
+ });
792
+ }
793
+ await (0, dialog_run_state_1.setDialogRunState)(dlg.id, nextIdle);
794
+ release();
795
+ }
796
+ }
797
+ async function runShowingByDoingLive(dlg) {
798
+ const release = await dlg.acquire();
799
+ const createdAt = (0, time_1.formatUnifiedTimestamp)(new Date());
800
+ const language = (0, runtime_language_1.getWorkLanguage)();
801
+ try {
802
+ await (0, dialog_run_state_1.setDialogRunState)(dlg.id, { kind: 'proceeding' });
803
+ const team = await team_1.Team.load();
804
+ const member = team.getMember(dlg.agentId);
805
+ const specialists = team.shellSpecialists
806
+ .filter((s) => typeof s === 'string')
807
+ .map((s) => s.trim())
808
+ .filter((s) => s !== '');
809
+ const selfIsShellSpecialist = specialists.includes(dlg.agentId);
810
+ const specialistId = specialists.find((s) => s !== dlg.agentId) ?? null;
811
+ const shellPolicy = specialists.length < 1
812
+ ? 'no_specialist'
813
+ : selfIsShellSpecialist
814
+ ? 'self_is_specialist'
815
+ : 'specialist_only';
816
+ const shellTellaskBody = formatShellTellaskBody(language);
817
+ let shellResponseText = '';
818
+ let snapshotText = '';
819
+ let directNoteMarkdown = '';
820
+ let shellCallId = null;
821
+ let shellTellaskHead = null;
822
+ let shellTellaskBodyForSubdialog = null;
823
+ // Phase 1: shell ask (and optional prelude intro)
824
+ try {
825
+ await dlg.notifyGeneratingStart();
826
+ await emitUiOnlyMarkdownEventsAndPersist(dlg, formatPreludeIntro(language, false, shellPolicy));
827
+ if (shellPolicy === 'specialist_only' && specialistId !== null) {
828
+ const shellCallSaying = [
829
+ `!?@${specialistId}`,
830
+ ...prefixTellaskBodyLines(shellTellaskBody).split('\n'),
831
+ '',
832
+ ].join('\n');
833
+ const calls = await emitSayingEventsAndPersist(dlg, shellCallSaying);
834
+ const call = calls.find((c) => c.validation.kind === 'valid');
835
+ if (!call) {
836
+ throw new Error('Failed to emit shell specialist tellask call');
837
+ }
838
+ shellCallId = call.callId;
839
+ shellTellaskHead = call.tellaskHead;
840
+ shellTellaskBodyForSubdialog = call.body;
841
+ }
842
+ else {
843
+ // Either no shell specialist is configured, or the dialog owner is itself a shell specialist.
844
+ // In both cases we skip the shell Tellask step and let the runtime capture a baseline snapshot.
845
+ // Keep it safe and deterministic: no network, no writes.
846
+ const unameOutput = await runUnameA();
847
+ shellResponseText = unameOutput;
848
+ snapshotText = unameOutput;
849
+ const directNote = (() => {
850
+ if (shellPolicy === 'self_is_specialist') {
851
+ return language === 'zh'
852
+ ? [
853
+ '由 Dominds 运行时执行:`uname -a`',
854
+ '',
855
+ '```console',
856
+ unameOutput,
857
+ '```',
858
+ '',
859
+ ].join('\n')
860
+ : ['Dominds runtime ran: `uname -a`', '', '```console', unameOutput, '```', ''].join('\n');
861
+ }
862
+ return language === 'zh'
863
+ ? [
864
+ '未配置 `shell_specialist`:由 Dominds 运行时仅执行基线命令 `uname -a` 以获取环境快照。',
865
+ '约束:后续**不得执行任意 shell 命令**;只能通过文件读写等非 shell 工具推进。',
866
+ '',
867
+ '```console',
868
+ unameOutput,
869
+ '```',
870
+ '',
871
+ ].join('\n')
872
+ : [
873
+ 'No `shell_specialist` configured: Dominds runtime ran only the baseline command `uname -a` to capture an environment snapshot.',
874
+ 'Constraint: do **not** run arbitrary shell commands; proceed only with non-shell tools like file read/write.',
875
+ '',
876
+ '```console',
877
+ unameOutput,
878
+ '```',
879
+ '',
880
+ ].join('\n');
881
+ })();
882
+ directNoteMarkdown = directNote;
883
+ await emitSayingEventsAndPersist(dlg, directNoteMarkdown);
884
+ }
885
+ }
886
+ finally {
887
+ try {
888
+ await dlg.notifyGeneratingFinish();
889
+ }
890
+ catch (_finishErr) {
891
+ // best-effort
892
+ }
893
+ }
894
+ // Phase 2: shell response (separate bubble)
895
+ if (shellPolicy === 'specialist_only' &&
896
+ specialistId !== null &&
897
+ shellCallId &&
898
+ shellTellaskHead) {
899
+ const tellaskBody = shellTellaskBodyForSubdialog ?? shellTellaskBody;
900
+ const sub = await dlg.createSubDialog(specialistId, shellTellaskHead, tellaskBody, {
901
+ originMemberId: dlg.agentId,
902
+ callerDialogId: dlg.id.selfId,
903
+ callId: shellCallId,
904
+ collectiveTargets: [specialistId],
905
+ });
906
+ const initPrompt = (0, inter_dialog_format_1.formatAssignmentFromSupdialog)({
907
+ fromAgentId: dlg.agentId,
908
+ toAgentId: sub.agentId,
909
+ tellaskHead: shellTellaskHead,
910
+ tellaskBody,
911
+ language,
912
+ collectiveTargets: [specialistId],
913
+ });
914
+ await (0, driver_1.driveDialogStream)(sub, { content: initPrompt, msgId: (0, id_1.generateShortId)(), grammar: 'markdown' }, true);
915
+ shellResponseText = extractLastAssistantSaying(sub.msgs);
916
+ const toolResult = extractLastShellCmdResultText(sub.msgs);
917
+ snapshotText = toolResult ? toolResult : shellResponseText;
918
+ if (!snapshotText.trim()) {
919
+ // Specialist produced no usable output (misconfigured tools, provider issues, etc.).
920
+ // Fall back to a runtime-executed `uname -a` so we can still proceed to FBR.
921
+ snapshotText = await runUnameA();
922
+ }
923
+ await dlg.receiveTeammateResponse(specialistId, shellTellaskHead, 'completed', sub.id, {
924
+ response: shellResponseText,
925
+ agentId: specialistId,
926
+ callId: shellCallId,
927
+ originMemberId: dlg.agentId,
928
+ });
929
+ }
930
+ const rawFbrEffort = member ? member.fbr_effort : undefined;
931
+ const fbrEffort = (() => {
932
+ if (typeof rawFbrEffort !== 'number' || !Number.isFinite(rawFbrEffort))
933
+ return 3;
934
+ const n = Math.floor(rawFbrEffort);
935
+ if (n < 0)
936
+ return 0;
937
+ if (n > 100)
938
+ return 100;
939
+ return n;
940
+ })();
941
+ const snapshotBody = formatFbrTellaskBody(language, BASELINE_ENV_SNAPSHOT_CMD, snapshotText, shellPolicy, { fbrEffort });
942
+ let fbrCallId = null;
943
+ let fbrTellaskHead = null;
944
+ const fbrResponses = [];
945
+ // Phase 3: FBR ask (call bubble)
946
+ if (fbrEffort >= 1) {
947
+ try {
948
+ await dlg.notifyGeneratingStart();
949
+ const fbrSaying = ['!?@self', ...prefixTellaskBodyLines(snapshotBody).split('\n'), ''].join('\n');
950
+ const fbrCalls = await emitSayingEventsAndPersist(dlg, fbrSaying);
951
+ const fbrCall = fbrCalls.find((c) => c.validation.kind === 'valid');
952
+ if (!fbrCall) {
953
+ throw new Error('Failed to emit FBR tellask call');
954
+ }
955
+ fbrCallId = fbrCall.callId;
956
+ fbrTellaskHead = fbrCall.tellaskHead;
957
+ }
958
+ finally {
959
+ try {
960
+ await dlg.notifyGeneratingFinish();
961
+ }
962
+ catch (_finishErr) {
963
+ // best-effort
964
+ }
965
+ }
966
+ // Phase 4: FBR responses (separate bubbles, stable index order)
967
+ if (!fbrCallId || !fbrTellaskHead) {
968
+ throw new Error('Missing FBR callId/tellaskHead');
969
+ }
970
+ const ensuredFbrCallId = fbrCallId;
971
+ const ensuredFbrTellaskHead = fbrTellaskHead;
972
+ const perInstance = Array.from({ length: fbrEffort }, (_, idx) => idx + 1);
973
+ const created = await Promise.all(perInstance.map(async (i) => {
974
+ const instanceBody = fbrEffort > 1
975
+ ? [
976
+ snapshotBody,
977
+ '',
978
+ language === 'zh'
979
+ ? '提示:请尽量提供与其它 FBR 草稿不同的视角(例如安全/限制/可验证性/工具优先级/风险点)。'
980
+ : 'Hint: try to provide a distinct angle vs other FBR drafts (e.g. security/constraints/verifiability/tool priority/risk).',
981
+ ].join('\n')
982
+ : snapshotBody;
983
+ const sub = await dlg.createSubDialog(dlg.agentId, ensuredFbrTellaskHead, instanceBody, {
984
+ originMemberId: dlg.agentId,
985
+ callerDialogId: dlg.id.selfId,
986
+ callId: ensuredFbrCallId,
987
+ collectiveTargets: [dlg.agentId],
988
+ });
989
+ const initPrompt = (0, inter_dialog_format_1.formatAssignmentFromSupdialog)({
990
+ fromAgentId: dlg.agentId,
991
+ toAgentId: sub.agentId,
992
+ tellaskHead: ensuredFbrTellaskHead,
993
+ tellaskBody: instanceBody,
994
+ language,
995
+ collectiveTargets: [dlg.agentId],
996
+ });
997
+ await (0, driver_1.driveDialogStream)(sub, { content: initPrompt, msgId: (0, id_1.generateShortId)(), grammar: 'markdown' }, true);
998
+ const responseText = extractLastAssistantSaying(sub.msgs);
999
+ return { sub, responseText };
1000
+ }));
1001
+ const shuffled = shuffleCopy(created);
1002
+ for (const r of shuffled) {
1003
+ const responseText = r.responseText;
1004
+ fbrResponses.push(responseText);
1005
+ await dlg.receiveTeammateResponse(dlg.agentId, ensuredFbrTellaskHead, 'completed', r.sub.id, {
1006
+ response: responseText,
1007
+ agentId: dlg.agentId,
1008
+ callId: ensuredFbrCallId,
1009
+ originMemberId: dlg.agentId,
1010
+ });
1011
+ }
1012
+ }
1013
+ const primingNote = await generatePrimingNoteViaMainlineAgent({
1014
+ dlg,
1015
+ snapshotCmd: BASELINE_ENV_SNAPSHOT_CMD,
1016
+ snapshotText,
1017
+ fbrResponses,
1018
+ shellPolicy,
1019
+ fbrEffort,
1020
+ });
1021
+ // Phase 5: summary bubble
1022
+ try {
1023
+ await dlg.notifyGeneratingStart();
1024
+ await emitSayingEventsAndPersist(dlg, primingNote);
1025
+ }
1026
+ finally {
1027
+ try {
1028
+ await dlg.notifyGeneratingFinish();
1029
+ }
1030
+ catch (_finishErr) {
1031
+ // best-effort
1032
+ }
1033
+ }
1034
+ const entry = {
1035
+ createdAt,
1036
+ workLanguage: language,
1037
+ shellPolicy,
1038
+ shell: shellPolicy === 'specialist_only' && specialistId !== null
1039
+ ? {
1040
+ kind: 'specialist_tellask',
1041
+ specialistId,
1042
+ tellaskBody: shellTellaskBody,
1043
+ responseText: shellResponseText,
1044
+ snapshotText,
1045
+ }
1046
+ : {
1047
+ kind: 'direct_shell',
1048
+ directNoteMarkdown,
1049
+ snapshotText,
1050
+ },
1051
+ fbr: {
1052
+ tellaskHead: '@self',
1053
+ tellaskBody: snapshotBody,
1054
+ responderAgentId: dlg.agentId,
1055
+ effort: fbrEffort,
1056
+ responses: fbrResponses,
1057
+ },
1058
+ primingNote,
1059
+ };
1060
+ dlg.setCoursePrefixMsgs(buildCoursePrefixMsgs(entry));
1061
+ return entry;
1062
+ }
1063
+ catch (err) {
1064
+ log_1.log.warn('Showing-by-Doing live run failed (best-effort)', err, { dialogId: dlg.id.valueOf() });
1065
+ const msg = language === 'zh'
1066
+ ? '做给祂看序幕执行失败(已跳过)。你可以继续正常对话。'
1067
+ : 'Showing-by-Doing prelude failed (skipped). You can continue normally.';
1068
+ try {
1069
+ await dlg.notifyGeneratingStart();
1070
+ await emitSayingEventsAndPersist(dlg, msg);
1071
+ await dlg.notifyGeneratingFinish();
1072
+ }
1073
+ catch (_emitErr) {
1074
+ // best-effort
1075
+ }
1076
+ throw err;
1077
+ }
1078
+ finally {
1079
+ let nextIdle = { kind: 'idle_waiting_user' };
1080
+ try {
1081
+ nextIdle = await (0, dialog_run_state_1.computeIdleRunState)(dlg);
1082
+ }
1083
+ catch (err) {
1084
+ log_1.log.warn('Failed to compute idle runState after Showing-by-Doing live run; falling back', err, {
1085
+ dialogId: dlg.id.valueOf(),
1086
+ });
1087
+ }
1088
+ await (0, dialog_run_state_1.setDialogRunState)(dlg.id, nextIdle);
1089
+ release();
1090
+ }
1091
+ }