ai_co_discuss 0.5.2 → 0.5.4

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 (94) hide show
  1. package/.agents/skills/discuss-host/SKILL.md +1 -1
  2. package/.agents/skills/discuss-host/references/control.md +9 -3
  3. package/.agents/skills/discuss-host/references/workflow.md +4 -1
  4. package/.agents/skills/discuss-participant/SKILL.md +3 -2
  5. package/.agents/skills/discuss-participant/references/interactive-html.md +93 -0
  6. package/.agents/skills/discuss-participant/references/writing.md +1 -1
  7. package/.agents/skills/workflow-creator/SKILL.md +10 -2
  8. package/.agents/skills/workflow-creator/references/model-selection.md +1 -1
  9. package/backend/free_room.py +123 -12
  10. package/backend/message_queue.py +1 -1
  11. package/backend/schema.sql +27 -0
  12. package/backend/server.py +76 -4
  13. package/docs/deployment.md +22 -0
  14. package/docs/en/deployment.md +22 -0
  15. package/docs/en/guide/admin.md +4 -3
  16. package/docs/en/guide/external-members.md +1 -1
  17. package/docs/en/guide/faq.md +11 -6
  18. package/docs/en/guide/members.md +4 -4
  19. package/docs/en/guide/rooms.md +14 -4
  20. package/docs/en/guide/scheduling.md +3 -4
  21. package/docs/en/guide/workflows.md +6 -3
  22. package/docs/en/guide/working.md +9 -5
  23. package/docs/guide/admin.md +4 -3
  24. package/docs/guide/external-members.md +1 -1
  25. package/docs/guide/faq.md +11 -6
  26. package/docs/guide/members.md +4 -4
  27. package/docs/guide/rooms.md +15 -5
  28. package/docs/guide/scheduling.md +3 -4
  29. package/docs/guide/workflows.md +6 -3
  30. package/docs/guide/working.md +9 -5
  31. package/frontend/locales/en/admin.json +33 -2
  32. package/frontend/locales/en/app.json +107 -1
  33. package/frontend/locales/en/backend.json +15 -1
  34. package/frontend/locales/en/core.json +14 -3
  35. package/frontend/locales/en/discussion.json +18 -2
  36. package/frontend/locales/en/room.json +37 -2
  37. package/frontend/locales/en/settings.json +13 -6
  38. package/gateway/gateway.mjs +11 -0
  39. package/gateway/login_page.mjs +77 -9
  40. package/package.json +3 -3
  41. package/runner/adapters/index.mjs +10 -0
  42. package/runner/adapters/profiles.mjs +23 -0
  43. package/runner/admin_cli.mjs +21 -5
  44. package/runner/admin_panel.mjs +64 -19
  45. package/runner/discuss.py +11 -2
  46. package/runner/discussion_launch.mjs +241 -44
  47. package/runner/discussion_local.mjs +2 -1
  48. package/runner/discussion_service.mjs +15 -7
  49. package/runner/discussion_skills.mjs +8 -0
  50. package/runner/expert_prompts.mjs +1 -2
  51. package/runner/files.mjs +17 -2
  52. package/runner/free_runner.mjs +23 -9
  53. package/runner/host_permissions.mjs +57 -0
  54. package/runner/hosting_tunnel.mjs +25 -7
  55. package/runner/i18n_en.mjs +39 -1
  56. package/runner/instance_recovery.mjs +78 -0
  57. package/runner/os_users.mjs +6 -1
  58. package/runner/relay_channel.mjs +121 -30
  59. package/runner/relay_health.mjs +100 -0
  60. package/runner/relay_health_text.mjs +44 -0
  61. package/runner/remote_launch.mjs +24 -14
  62. package/runner/scheduler.mjs +45 -102
  63. package/runner/session_driver.mjs +3 -4
  64. package/runner/workflow_flow.mjs +32 -2
  65. package/runner/workflows.mjs +84 -21
  66. package/web/admin.css +1 -1
  67. package/web/admin.js +3 -3
  68. package/web/app.js +974 -194
  69. package/web/backup.js +1 -1
  70. package/web/i18n.js +4 -4
  71. package/web/markdown.js +2 -2
  72. package/web/modern.css +1 -1
  73. package/web/modern.js +78 -63
  74. package/workflows/story-serial/SKILL.md +7 -5
  75. package/workflows/story-serial/agents/recorder.md +6 -5
  76. package/workflows/story-serial/agents/writer.md +1 -1
  77. package/workflows/story-serial/commands.json +1 -1
  78. package/workflows/story-serial/templates/README.md +3 -3
  79. package/workflows/story-serial/templates//344/270/226/347/225/214.md +1 -1
  80. package/workflows/story-serial/templates//345/267/245/344/275/234/345/217/260.md +3 -3
  81. package/workflows/story-serial/templates//346/216/222/347/272/277/350/241/250.md +2 -2
  82. package/workflows/story-serial/templates//346/226/207/351/243/216.md +1 -1
  83. package/workflows/story-serial/templates//347/212/266/346/200/201//344/270/273/350/247/222.yaml +2 -2
  84. package/workflows/story-serial/templates//347/212/266/346/200/201//344/272/272/347/211/251.yaml +1 -1
  85. package/workflows/story-serial/templates//347/212/266/346/200/201//345/210/206/351/233/206/350/256/260/345/275/225.yaml +1 -1
  86. package/workflows/story-serial/templates//347/212/266/346/200/201//346/215/256/347/202/271.yaml +1 -1
  87. package/workflows/story-serial/templates//347/212/266/346/200/201//347/211/251/350/265/204.yaml +3 -3
  88. package/workflows/story-serial/templates//347/212/266/346/200/201//347/272/277/347/264/242.yaml +4 -3
  89. package/workflows/story-serial/tools//347/212/266/346/200/201/346/243/200/346/237/245.py +81 -7
  90. package/workflows/story-serial/workflows/revise-episodes/SKILL.md +9 -4
  91. package/workflows/story-serial/workflows/revise-episodes/flow.json +93 -0
  92. package/workflows/story-serial/workflows/tidy-docs/SKILL.md +55 -0
  93. package/workflows/story-serial/workflows/tidy-docs/flow.json +74 -0
  94. package/workflows/story-serial/workflows/tidy-docs/references//346/226/207/346/241/243/346/240/207/345/207/206.md +97 -0
@@ -11,6 +11,8 @@ import { setTimeout as sleep } from 'node:timers/promises';
11
11
  import { cleanup_room, sweep_adapters } from './adapters/index.mjs';
12
12
  import { same_session_family } from './adapters/profiles.mjs';
13
13
  import { atomic_json } from './files.mjs';
14
+ import { relay_health_writer } from './relay_health.mjs';
15
+ import { t } from './i18n.mjs';
14
16
  import { DiscussionStore, acquire_lock, api, load_config, pause_if_running, service_drafts, validate_config } from './discussion_runner.mjs';
15
17
  import { FreeRoomRunner, write_proactive_access } from './free_runner.mjs';
16
18
  import { can_notify, notice_sent, receive_replies, send_notice } from './weixin.mjs';
@@ -37,7 +39,8 @@ const REMOTE_SYNC_MS = 3000;
37
39
  // A relayed-command claim that waited at least this long is followed by the next one at once.
38
40
  const RELAY_RESTART_MIN_MS = 1000;
39
41
  const START_WAIT_MS = 5000;
40
- const STOP_WAIT_MS = 20_000;
42
+ // Pausing every room's running work before exit can take this long when many rooms are busy (an update stops it).
43
+ const STOP_WAIT_MS = 60_000;
41
44
  // Left by `service stop` and cleared by any start: the local supervisor restarts a service that exited only without it.
42
45
  const STOPPED_MARKER = 'service.stopped';
43
46
  const REGISTRY_WAIT_MS = 5000;
@@ -755,7 +758,8 @@ export async function run_service(home, output = () => {}) {
755
758
  const { relay_commands, sync_remote_launches } = await import('./remote_launch.mjs');
756
759
  const { start_relay_channels } = await import('./relay_channel.mjs');
757
760
  if ((await import('./admin_account.mjs')).remove_legacy_admin_accounts(home)) log_line('已删除旧版本明文保存的管理员密码文件 admin-accounts.json');
758
- channels = start_relay_channels(home, { log: log_line, signal: relay_stop.signal });
761
+ const health = relay_health_writer(home);
762
+ channels = start_relay_channels(home, { log: log_line, signal: relay_stop.signal, health });
759
763
  // A hosted account reached on its owner's domain answers external members here instead of over the relay (#5588).
760
764
  direct = (await import('./direct_entry.mjs')).direct_receiver(home, { log: log_line });
761
765
  direct.refresh();
@@ -764,14 +768,14 @@ export async function run_service(home, output = () => {}) {
764
768
  // The owner's Weixin replies come back here and go to the room their notice came from.
765
769
  receiving = receive_replies(home, { on_reply: reply => service.weixin_reply(reply), log: log_line, signal: relay_stop.signal })
766
770
  .catch(error => log_line(`微信收件停止:${error.message}`));
767
- let synced_at = 0, swept_at = 0, relay_failed_at = 0;
771
+ let synced_at = 0, channels_checked_at = 0, swept_at = 0, relay_failed_at = 0;
768
772
  // A long-poll of its own: the site answers as soon as another device relays a command, and the next claim starts
769
773
  // the moment one returns, so a device sending several commands never waits on the loop; a failure retries after the sync interval.
770
774
  // A claim that returned at once (no paired site, or a command already queued) goes back to the loop instead, so nothing spins.
771
775
  const start_relay = () => {
772
776
  let failed = false;
773
777
  const started = Date.now();
774
- relaying = relay_commands(home, { log: log_line, signal: relay_stop.signal, skip: channels.connected,
778
+ relaying = relay_commands(home, { log: log_line, signal: relay_stop.signal, skip: channels.connected, health,
775
779
  on_failure: () => { failed = true; relay_failed_at = Date.now(); } })
776
780
  .catch(error => { failed = true; relay_failed_at = Date.now(); log_line(`远程命令检查失败:${error.message}`); })
777
781
  .finally(() => {
@@ -791,14 +795,18 @@ export async function run_service(home, output = () => {}) {
791
795
  } catch (error) { log_line(`清理本机文件失败:${error.message}`); }
792
796
  }
793
797
  // Runs beside the room ticks: a slow remote site must not hold up local rooms.
798
+ if (Date.now() - channels_checked_at >= REMOTE_SYNC_MS) {
799
+ channels_checked_at = Date.now();
800
+ try { channels.refresh(); } catch (error) { log_line(t('检查中转连接失败:{reason}', { reason: error.message })); }
801
+ }
794
802
  if (!syncing && Date.now() - synced_at >= REMOTE_SYNC_MS) {
795
803
  synced_at = Date.now();
796
- channels.refresh();
797
804
  direct.refresh();
798
- syncing = sync_remote_launches(home, { log: log_line, throttle: true }).catch(error => log_line(`远程启动检查失败:${error.message}`))
805
+ syncing = sync_remote_launches(home, { log: log_line, throttle: true, health }).catch(error => log_line(`远程启动检查失败:${error.message}`))
799
806
  .finally(() => { syncing = null; });
800
807
  }
801
808
  if (!relaying && Date.now() - relay_failed_at >= REMOTE_SYNC_MS) start_relay();
809
+ try { health.flush(); } catch (error) { log_line(t('写中转状态失败:{reason}', { reason: error.message })); }
802
810
  // Pi, which runs model API members, is the release this codiscuss version pins; after a codiscuss upgrade pins
803
811
  // another, it is installed once, in the background. A release that fails its check is not switched to.
804
812
  if (!pi_checked && !process.env.CODISCUSS_PI_CLI) {
@@ -887,7 +895,7 @@ async function stop_service(home) {
887
895
  if (!service_pid(home)) return { running: false };
888
896
  await sleep(500);
889
897
  }
890
- throw new Error('讨论服务未在 20 秒内退出;请查看 service.log');
898
+ throw new Error('讨论服务未在 60 秒内退出;请查看 service.log');
891
899
  }
892
900
 
893
901
  /** Report liveness with the last per-room result written by the service. */
@@ -103,6 +103,14 @@ export function shipped_workflows() {
103
103
  });
104
104
  }
105
105
 
106
+ /** The shipped workflows a service home has whose copy differs from the shipped version (edited or older). */
107
+ export function outdated_workflows(home) {
108
+ return shipped_workflows().map(item => item.name).filter(name => {
109
+ const destination = workflow_directory(home, name);
110
+ return existsSync(destination) && tree_hash(destination) !== tree_hash(join(WORKFLOW_SOURCE, name));
111
+ });
112
+ }
113
+
106
114
  /**
107
115
  * Install shipped workflows into the service home's library, replacing any of the same ID with the shipped version.
108
116
  * Setup calls this only for the ones the user picks on that run; a copy that differs is backed up first.
@@ -85,8 +85,7 @@ export const TASK_SUBCOMMANDS = ['room', 'message', 'turn', 'state', 'goal', 'mo
85
85
  * The limit on a quick answer given inline with --body: a run allowed only codiscuss commands refuses a command line
86
86
  * carrying shell symbols, and PowerShell rewrites `$` and backticks inside quotes. The participant skill says the same.
87
87
  */
88
- export const INLINE_BODY_RULE = '--body 的正文不能含反引号、英文括号、$、;、&、|、<、> 或换行,含这些时写草稿再用 --body-file';
89
-
88
+ export const INLINE_BODY_RULE = '--body 只用于不超过 200 字的短答,不能含反引号、英文括号、$、;、&、|、<、> 或换行,否则写草稿再用 --body-file';
90
89
  // How many times one execution is resumed to correct commands it can fix itself (2026-11-19 user: three).
91
90
  export const MAX_REFUSAL_RETRIES = 3;
92
91
  const REFUSED_COMMAND_SHOWN = 200;
package/runner/files.mjs CHANGED
@@ -1,10 +1,25 @@
1
1
  /** Small private files the runner keeps on this machine. */
2
2
  import { randomUUID } from 'node:crypto';
3
- import { renameSync, writeFileSync } from 'node:fs';
3
+ import { renameSync, rmSync, writeFileSync } from 'node:fs';
4
+
5
+ // On Windows a rename over a file another process has open (a reader polling it, an exiting service) fails for a moment
6
+ // with EPERM, EACCES or EBUSY; retry that briefly instead of failing the caller (it once stopped a hosted instance).
7
+ const RENAME_BUSY = new Set(['EPERM', 'EACCES', 'EBUSY']);
8
+ const RENAME_TRIES = 20;
9
+ const RENAME_WAIT_MS = 50;
4
10
 
5
11
  /** Persist small private state atomically without logging its contents. */
6
12
  export function atomic_json(path, value) {
7
13
  const temporary = `${path}.${randomUUID()}.tmp`;
8
14
  writeFileSync(temporary, JSON.stringify(value, null, 2), { mode: 0o600 });
9
- renameSync(temporary, path);
15
+ for (let attempt = 1; ; attempt += 1) {
16
+ try { return renameSync(temporary, path); }
17
+ catch (error) {
18
+ if (!RENAME_BUSY.has(error.code) || attempt >= RENAME_TRIES) {
19
+ rmSync(temporary, { force: true });
20
+ throw error;
21
+ }
22
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, RENAME_WAIT_MS);
23
+ }
24
+ }
10
25
  }
@@ -3,7 +3,7 @@ import { spawnSync } from 'node:child_process';
3
3
  import { createHash, randomUUID } from 'node:crypto';
4
4
  import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
5
5
  import { basename, join, resolve } from 'node:path';
6
- import { adapter_of, BRANCHABLE_ADAPTERS, branch_session, capabilities_of, cleanup_room, deliver_task, delivery_receipt, recover_turn, session_exists, stored_delivery, takes_images } from './adapters/index.mjs';
6
+ import { adapter_of, BRANCHABLE_ADAPTERS, branch_session, capabilities_of, chosen_settings, cleanup_room, deliver_task, delivery_receipt, recover_turn, session_exists, session_settings, stored_delivery, takes_images } from './adapters/index.mjs';
7
7
  import { api as raw_api, overlapping_directories, read_rule } from './discussion_runner.mjs';
8
8
  import { SegmentLog } from './execution_progress.mjs';
9
9
  import { capture_base, file_diffs } from './file_diff.mjs';
@@ -15,9 +15,10 @@ import { outside_directory, room_directories } from './project_files.mjs';
15
15
  import { SessionDriver } from './session_driver.mjs';
16
16
  import { slash_names } from './slash_names.mjs';
17
17
  import { effective_profile, load_room_workflow, workflow_directory, workflow_in_use, workflow_task_field } from './workflows.mjs';
18
- import { DEFAULT_SCHEDULER_MODE, GOAL_PROMPT_VERSION, decide_goal_wake, decide_sequence_checkpoint, REVIEW_CONFIDENCE, REVIEW_PROMPT_VERSION, SEQUENCE_CONFIDENCE, SEQUENCE_PROMPT_VERSION, ROUTE_CONFIDENCE, ROUTE_CONTEXT_MESSAGES, decide_review_completion, route_free_message, route_prompt_version, scheduler_thresholds, some_members } from './scheduler.mjs';
18
+ import { GOAL_CONFIDENCE, GOAL_PROMPT_VERSION, decide_goal_wake, decide_sequence_checkpoint, REVIEW_CONFIDENCE, REVIEW_PROMPT_VERSION, SEQUENCE_CONFIDENCE, SEQUENCE_PROMPT_VERSION, ROUTE_CONFIDENCE, ROUTE_CONTEXT_MESSAGES, ROUTE_GUIDED_PROMPT_VERSION, ROUTE_WIDE_CONFIDENCE, SCHEDULER_MODE, decide_review_completion, route_free_message, some_members } from './scheduler.mjs';
19
19
  import { room_text, room_payload } from './room_text.mjs';
20
20
  import { question_notice } from './question_weixin.mjs';
21
+ import { host_permissions } from './host_permissions.mjs';
21
22
  const api = (config, path, payload, ...options) => raw_api(config, path, room_payload(payload), ...options);
22
23
 
23
24
  const PACKAGE_VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
@@ -385,14 +386,16 @@ export function free_task_files(config, member, execution, binding, { session =
385
386
  skills: skills.map(file => join(config.project, '.agents/skills', file)),
386
387
  // The workflow's SKILL.md is not a skill read on every task: the host opens it when a request fits its description.
387
388
  ...(workflow_field ? { workflow: { ...workflow_field, skill_path: host_workflow.skill_path } } : {}),
388
- ...(member.role === 'host' && config.host_workflows ? { host_workflows: true } : {}),
389
+ ...(member.role === 'host' && config.host_workflows ? { host_workflows: true, host_permissions: host_permissions(config).items } : {}),
389
390
  // Present only while the owner has drawing on and this computer has an image service.
390
391
  ...(image ? { image: { model: image.model, command: `${cli} launch image --file REQUEST.json` } } : {}),
391
392
  cli, subcommands: TASK_SUBCOMMANDS,
392
393
  ...(bound_access ? { access_env: 'DISCUSS_ACCESS_FILE' } : { access_file: access_path }), instructions });
393
394
  return { id, participant: member.name, directory: config.directory, member_directory, task_path, draft_directory, extra_directories, ...(goal_field ? { goal: goal_field } : {}),
394
395
  ...(goal_of_room ? { room_goal: goal_of_room } : {}),
395
- skill_directories: [skills_directory, ...(host_workflow ? [host_workflow.directory] : [])], access_path, prompt: with_expert_prompt(prompt, profile), inbox, images,
396
+ // Every member may read the folder of the room's workflow (templates, tools, a review of the workflow itself), also
397
+ // while its members are away and the host no longer follows it; only the host's task names it.
398
+ skill_directories: [skills_directory, ...(workflow && !workflow.error ? [workflow.directory] : [])], access_path, prompt: with_expert_prompt(prompt, profile), inbox, images,
396
399
  profile, ...(workflow_field ? { workflow: { ...workflow_field, skill: host_workflow.skill, ...api_sub_workflows(workflow_field, host_workflow) } } : {}) };
397
400
  }
398
401
 
@@ -826,7 +829,7 @@ export class FreeRoomRunner {
826
829
  } catch (error) { this.log(`Goal ${action === 'wait' ? '等待' : '续跑'}未生效:${error.message}`); }
827
830
  finally { this.goal_idle = null; }
828
831
  if (decision?.detail) await this.record_decision(decision.after_message_id, decision, decision.label, applied,
829
- { prompt: GOAL_PROMPT_VERSION, threshold: ROUTE_CONFIDENCE, wide_threshold: ROUTE_CONFIDENCE, scene: 'goal' });
832
+ { prompt: GOAL_PROMPT_VERSION, threshold: GOAL_CONFIDENCE, wide_threshold: GOAL_CONFIDENCE, scene: 'goal' });
830
833
  }
831
834
  /** The Weixin notice an active goal waiting on the owner calls for, or null. */
832
835
  pending_notice(room) {
@@ -1025,12 +1028,11 @@ export class FreeRoomRunner {
1025
1028
  }
1026
1029
  /** Show each judgment under its message so the user can rate it; a failed record never affects delivery. */
1027
1030
  async record_decision(message_id, decision, label, applied, context = {}) {
1028
- const limits = scheduler_thresholds(this.config.scheduler.mode || DEFAULT_SCHEDULER_MODE);
1029
1031
  try {
1030
1032
  return await api(this.config, '/scheduler-decisions', { kind: 'interjection', label, confidence: decision.confidence ?? null,
1031
1033
  applied, provider: this.config.scheduler.provider, after_message_id: message_id, detail: decision.detail, input: decision.input,
1032
- context: { model: this.config.scheduler.model, threshold: limits.member, wide_threshold: limits.wide,
1033
- mode: this.config.scheduler.mode || DEFAULT_SCHEDULER_MODE, prompt: route_prompt_version(this.config.scheduler.mode || DEFAULT_SCHEDULER_MODE), package: PACKAGE_VERSION, ...context } });
1034
+ context: { model: this.config.scheduler.model, threshold: ROUTE_CONFIDENCE, wide_threshold: ROUTE_WIDE_CONFIDENCE,
1035
+ mode: SCHEDULER_MODE, prompt: ROUTE_GUIDED_PROMPT_VERSION, package: PACKAGE_VERSION, ...context } });
1034
1036
  } catch (error) { this.log(`智能调度 #${message_id} 决策记录未保存:${error.message}`); }
1035
1037
  }
1036
1038
  /** Reserve with a persisted client id before invoking any software. */
@@ -1185,6 +1187,7 @@ export class FreeRoomRunner {
1185
1187
  const delivery = result.capabilities || capabilities_of(adapter.adapter).delivery;
1186
1188
  await this.report_delivery(execution.id, { ...delivery, steer: Boolean(result.steer),
1187
1189
  resume: Boolean(capabilities_of(adapter.adapter).resume && delivery.stoppable) }, member.name);
1190
+ this.report_model(execution.id, chosen_settings(task.profile));
1188
1191
  } catch (error) {
1189
1192
  if (review_request && error.delivery_status === 'not_sent') return this.reject_review(member, execution, error.message);
1190
1193
  if (adapter.project_access === 'own') return this.retry_or_fail(member.name, execution, `投递失败:${error.message}`);
@@ -1439,6 +1442,12 @@ export class FreeRoomRunner {
1439
1442
  await api(this.config, `/executions/${execution_id}`, { action: 'delivery', stoppable, progress, steer, resume })
1440
1443
  .catch(error => this.log(`执行 #${execution_id} 的投递能力未能上报:${error.message}`));
1441
1444
  }
1445
+ /** Tell the site which model and effort an execution ran with, for its card; a lost report only leaves the card without it. */
1446
+ report_model(execution_id, { model, effort }) {
1447
+ if (!model && !effort) return;
1448
+ api(this.config, `/executions/${execution_id}`, { action: 'model', model, effort })
1449
+ .catch(error => this.log(`执行 #${execution_id} 的模型未能上报:${error.message}`));
1450
+ }
1442
1451
  /** Retry durable stop reports even after the member went idle, left, or started a later execution. */
1443
1452
  async report_stops(active) {
1444
1453
  const pending = new Set();
@@ -1596,7 +1605,12 @@ export class FreeRoomRunner {
1596
1605
  const running = this.execution_processes.get(execution_id)?.size > 0;
1597
1606
  if (running && snapshot.reported_early) continue;
1598
1607
  if (running) snapshot.reported_early = true;
1599
- else this.snapshots.delete(execution_id);
1608
+ else {
1609
+ this.snapshots.delete(execution_id);
1610
+ // Once the turn is over the software's session log says what really ran (a default model, or one the App chose).
1611
+ const profile = this.config.participants[snapshot.member];
1612
+ if (profile) this.report_model(execution_id, session_settings(profile.adapter, this.store.binding(snapshot.member).session_id));
1613
+ }
1600
1614
  const after = snapshot.before ? workspace_snapshot(snapshot.directory) : null;
1601
1615
  const extra = (snapshot.extras || []).flatMap(item => {
1602
1616
  const current = workspace_snapshot(item.directory);
@@ -0,0 +1,57 @@
1
+ // What the owner lets a room's AI host do by itself, item by item. Free of Node dependencies: the web page lists the
2
+ // same items in the new-room form and the room settings. Kept in the runner's room configuration as
3
+ // `host_permissions: { items, room_limit }`; the older `host_workflows: true` alone means every item it used to cover.
4
+
5
+ /** Items the older single switch covered, in the order screens list them. */
6
+ export const HOST_LEGACY_ITEMS = ['execution', 'member_config', 'project_access', 'roster', 'pacing', 'workflows'];
7
+ /** Every item; `create_rooms` is newer than the single switch, so an old room never has it until the owner ticks it. */
8
+ export const HOST_ITEMS = [...HOST_LEGACY_ITEMS, 'create_rooms'];
9
+ export const DEFAULT_HOST_ROOM_LIMIT = 3;
10
+ export const MAX_HOST_ROOM_LIMIT = 20;
11
+
12
+ /** The item each `host-control` action needs; actions not listed only read and are always allowed. */
13
+ export const HOST_ACTION_ITEMS = {
14
+ stop: 'execution', 'stop-all': 'execution', steer: 'execution', retry: 'execution', withdraw: 'execution',
15
+ model: 'member_config', adapter: 'member_config', label: 'member_config',
16
+ access: 'project_access',
17
+ invite: 'roster', away: 'roster', remove: 'roster', back: 'roster',
18
+ order: 'pacing', discussion: 'pacing', goal: 'pacing', checkin: 'pacing',
19
+ // `room-post` needs no item: it reaches only rooms linked by a `create-room` the owner allowed.
20
+ 'create-room': 'create_rooms',
21
+ };
22
+
23
+ const ITEM_LABELS = { execution: '处理执行问题', member_config: '调整成员配置', project_access: '改项目权限', roster: '管理成员名单',
24
+ pacing: '推进方式', workflows: '工作流', create_rooms: '新建房间' };
25
+
26
+ /**
27
+ * The permissions a stored value means, with unknown items dropped and the limit kept in range.
28
+ * @param {object} [value] A stored `host_permissions`.
29
+ * @param {boolean} [legacy_flag] The older `host_workflows`, used only when `value` is absent.
30
+ * @returns {{ items: string[], room_limit: number }}
31
+ */
32
+ export function normalize_host_permissions(value, legacy_flag = false) {
33
+ const listed = Array.isArray(value?.items) ? value.items : legacy_flag ? HOST_LEGACY_ITEMS : [];
34
+ const limit = Number.isInteger(value?.room_limit) ? value.room_limit : DEFAULT_HOST_ROOM_LIMIT;
35
+ return { items: HOST_ITEMS.filter(item => listed.includes(item)), room_limit: Math.max(1, Math.min(limit, MAX_HOST_ROOM_LIMIT)) };
36
+ }
37
+
38
+ /** A room configuration's host permissions. */
39
+ export const host_permissions = config => normalize_host_permissions(config?.host_permissions, config?.host_workflows === true);
40
+
41
+ /** Whether the owner lets this room's host do what `item` covers. */
42
+ export const host_allowed = (config, item) => host_permissions(config).items.includes(item);
43
+
44
+ /** How many rooms this room's host may create from it. */
45
+ export const host_room_limit = config => host_permissions(config).room_limit;
46
+
47
+ /** The same permissions without one item, e.g. a room the host created cannot create rooms itself. */
48
+ export const without_host_item = (permissions, item) => ({ ...permissions, items: permissions.items.filter(entry => entry !== item) });
49
+
50
+ /** The two configuration fields to store for these permissions; `host_workflows` stays as "any item granted". */
51
+ export function host_permission_fields(permissions) {
52
+ const next = normalize_host_permissions(permissions);
53
+ return { host_permissions: next.items.length ? next : undefined, host_workflows: next.items.length ? true : undefined };
54
+ }
55
+
56
+ /** What the host is told when the owner has not granted the item an action needs. */
57
+ export const host_refusal = item => `房主没有为本房间勾选主持人权限“${ITEM_LABELS[item]}”;请让用户在电脑上“成员与设置 → 协作设置 → 主持人权限”勾选后再试`;
@@ -11,7 +11,7 @@
11
11
  * computer only.
12
12
  */
13
13
  import { spawn, spawnSync } from 'node:child_process';
14
- import { closeSync, existsSync, mkdirSync, openSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
14
+ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
15
15
  import net from 'node:net';
16
16
  import { homedir } from 'node:os';
17
17
  import { join, resolve } from 'node:path';
@@ -90,6 +90,18 @@ function login_in_browser(cloudflared, { shown, on_url }) {
90
90
  });
91
91
  }
92
92
 
93
+ /**
94
+ * Point `host` at the tunnel and return the record name cloudflared reports (it logs to stderr), or '' when it names
95
+ * none. A failure is only reported: an existing record that already points at this tunnel is fine.
96
+ */
97
+ function route_dns(cloudflared, name, host, say) {
98
+ const result = spawnSync(cloudflared, ['tunnel', 'route', 'dns', name, host], { encoding: 'utf8', windowsHide: true });
99
+ const output = `${result.stdout || ''}\n${result.stderr || ''}`;
100
+ const record = output.match(/Added CNAME (\S+)/)?.[1] || output.match(/(\S+) is already configured to route/)?.[1] || '';
101
+ if (result.status !== 0) say(t('没有新建 {value1} 的域名记录({value2});若它已指向这条隧道可忽略', { value1: host, value2: output.trim().split(/\r?\n/).pop() || result.status }));
102
+ return record.toLowerCase();
103
+ }
104
+
93
105
  function run(cloudflared, args, shown = false) {
94
106
  const result = spawnSync(cloudflared, args, { encoding: 'utf8', windowsHide: !shown, stdio: shown ? TO_STDERR : 'pipe' });
95
107
  if (result.status !== 0) throw new Error(t('cloudflared {value1} 失败:{value2}', { value1: args.join(' '), value2: String(result.stderr || '').trim().split(/\r?\n/).pop() || t('退出码 {value1}', { value1: result.status }) }));
@@ -115,13 +127,14 @@ export async function prepare_tunnel({ host, name = DEFAULT_TUNNEL_NAME, interac
115
127
  host = tunnel_host(host); name = tunnel_name(name);
116
128
  progress(t('安装 cloudflared'));
117
129
  const cloudflared = install_cloudflared(shown);
118
- if (!existsSync(join(TUNNEL_HOME, 'cert.pem'))) {
130
+ const authorize = async () => {
119
131
  if (!interactive) throw new Error(t('还没有授权 Cloudflare:在管理面板“概览”页设置外网地址,或在终端运行 codiscuss setup --hosting,在浏览器里完成授权'));
120
132
  progress(t('等待 Cloudflare 授权'));
121
133
  say(t('即将打开浏览器:登录 Cloudflare,选择 {value1} 并点 Authorize,完成后回到这里', { value1: host.split('.').slice(-2).join('.') }));
122
134
  await login_in_browser(cloudflared, { shown, on_url });
123
135
  if (!existsSync(join(TUNNEL_HOME, 'cert.pem'))) throw new Error(t('Cloudflare 授权没有完成,重新开始即可再试'));
124
- }
136
+ };
137
+ if (!existsSync(join(TUNNEL_HOME, 'cert.pem'))) await authorize();
125
138
  progress(t('建立隧道'));
126
139
  let tunnel = find_tunnel(cloudflared, name);
127
140
  if (!tunnel) { run(cloudflared, ['tunnel', 'create', name]); tunnel = find_tunnel(cloudflared, name); }
@@ -129,10 +142,15 @@ export async function prepare_tunnel({ host, name = DEFAULT_TUNNEL_NAME, interac
129
142
  const credentials = join(TUNNEL_HOME, `${tunnel.id}.json`);
130
143
  if (!existsSync(credentials)) throw new Error(t('找不到隧道凭据 {value1}:这条隧道可能建在别的电脑上,换一个 --tunnel-name 重新运行', { value1: credentials }));
131
144
  progress(t('添加域名记录'));
132
- try { run(cloudflared, ['tunnel', 'route', 'dns', name, host]); }
133
- catch (error) {
134
- // An existing record that already points at this tunnel is fine; any other is reported by the final check.
135
- say(t('没有新建 {value1} 的域名记录({value2});若它已指向这条隧道可忽略', { value1: host, value2: error.message }));
145
+ let routed = route_dns(cloudflared, name, host, say);
146
+ if (routed && routed !== host) {
147
+ // The sign-in covers one Cloudflare domain; cloudflared then appends it to a host of another domain
148
+ // (test.b.com becomes test.b.com.a.com). Sign in again for the host's own domain, keeping the old one aside.
149
+ say(t('Cloudflare 授权的是另一个域名,记录被建成了 {value1}(可在 Cloudflare 删除);需要为 {value2} 重新授权', { value1: routed, value2: host }));
150
+ renameSync(join(TUNNEL_HOME, 'cert.pem'), join(TUNNEL_HOME, `cert-${Date.now()}.pem`));
151
+ await authorize();
152
+ routed = route_dns(cloudflared, name, host, say);
153
+ if (routed && routed !== host) throw new Error(t('授权的仍不是 {value1} 所在的域名,记录被建成了 {value2}:重新开始,在浏览器里选对域名', { value1: host, value2: routed }));
136
154
  }
137
155
  return { name, host, id: tunnel.id, credentials };
138
156
  }
@@ -1,5 +1,41 @@
1
1
  /** English CLI strings. */
2
2
  export default {
3
+ "自动重启失败:{reason}": "Automatic restart failed: {reason}",
4
+ "实例端口拒绝连接": "The instance port refused the connection",
5
+ "{site} 的中转连续 3 分钟未确认,正在重建连接。": "The relay to {site} has gone unconfirmed for 3 minutes. Rebuilding the connection.",
6
+ "正在按管理员要求重建 {site} 的中转连接。": "Rebuilding the relay connection to {site} at the administrator’s request.",
7
+ "检查中转连接失败:{reason}": "Could not check relay connections: {reason}",
8
+ "实例再次退出,自动重启已达上限。": "The instance exited again. The automatic restart limit has been reached.",
9
+ "实例端口拒绝连接,正在自动重启(第 {count} 次)。": "The instance port refused the connection. Starting automatic restart attempt {count}.",
10
+ "实例已自动重启。": "The instance was automatically restarted.",
11
+ "托管实例巡检失败:{reason}\n": "Hosted instance check failed: {reason}\n",
12
+ "尚未绑定线上网站": "No online site is bound yet",
13
+ "请先启动共议服务,再重连中转": "Start the CoDiscuss service before reconnecting the relay",
14
+ "暂时无法读取管理面板的最新状态。": "The latest management panel status could not be retrieved.",
15
+ "与 {host} 的中转连接失败({reason}),已重试 {retries} 次,HTTP 请求也已连续失败 {count} 次({http_reason})。": "The relay connection to {host} failed ({reason}). Retry count: {retries}. Also, {count} consecutive HTTP requests failed ({http_reason}).",
16
+ "正在等待 {host} 确认中转,HTTP 请求已连续失败 {count} 次({reason})。": "Waiting for relay confirmation from {host}. There have been {count} consecutive HTTP failures ({reason}).",
17
+ "状态未知": "Status unknown",
18
+ "共议服务未运行,无法确认中转状态。": "The CoDiscuss service is stopped. Relay status is unknown.",
19
+ "没有当前服务的近期中转记录。": "No recent relay status is available from the current service.",
20
+ "中转异常": "Relay failed",
21
+ "中转重连中": "Relay reconnecting",
22
+ "与 {host} 的中转连接失败({reason}),已重试 {retries} 次。": "The relay connection to {host} failed ({reason}). Retry count: {retries}.",
23
+ "网站请求异常": "Website requests failing",
24
+ "中转心跳正常,但向 {host} 发出的 HTTP 请求已连续失败 {count} 次({reason})。": "The relay heartbeat is healthy, but {count} consecutive HTTP requests to {host} failed ({reason}).",
25
+ "中转已连接": "Relay connected",
26
+ "中转连接中": "Relay connecting",
27
+ "正在等待 {host} 确认连接,上次失败原因是{reason},已重试 {retries} 次。": "Waiting for confirmation from {host}. Last failure: {reason}. Retry count: {retries}.",
28
+ "连接已打开,正在等待网站回应心跳。": "The connection is open. Waiting for the website to acknowledge the heartbeat.",
29
+ "正在连接 {host}。": "Connecting to {host}.",
30
+ "心跳超过 {seconds} 秒未回应": "no heartbeat response for {seconds} seconds",
31
+ "连接已断开,关闭代码 {code}": "connection closed with code {code}",
32
+ "连接被重置,请检查本机网络或代理": "connection reset; check this computer’s network or proxy",
33
+ "连接超时,请检查本机网络或代理": "connection timed out; check this computer’s network or proxy",
34
+ "无法解析网站域名": "website hostname could not be resolved",
35
+ "连接被拒绝": "connection refused",
36
+ "无法连接网站,请检查本机网络或代理": "website unreachable; check this computer’s network or proxy",
37
+ "未绑定": "Not bound",
38
+ "写中转状态失败:{reason}": "Could not write relay status: {reason}",
3
39
  "CLI 运行超过 {seconds} 秒仍未结束,已终止": "CLI exceeded the runtime limit of {seconds} seconds and was terminated",
4
40
  "room-invite 创建待签到席位并签发邀请;提供 member_id 时重发该席位链接,旧链接失效。须提供 room_id、token,可选 level(discuss/read)、folders、site_url(借出时间由被邀请方加入时决定);程序先读名单 revision 再建席位。链接有效 10 分钟,未签到席位 7 天结束;未绑定线上站点时只建立席位。": "room-invite reserves a seat and issues an invitation; member_id regenerates that seat's link and invalidates the old one. Requires room_id and token; optional level (discuss/read), folders, site_url (the invited computer chooses how long it lends its AI when joining). The runner reads the roster revision before creating a seat. Links last 10 minutes; unclaimed seats end after 7 days. Without a connected hosted site, only the seat is created.",
5
41
  "连不上 {host}:{seconds} 秒内没有响应,请检查这台电脑的网络或代理后重试": "Cannot connect to {host}: no response within {seconds} seconds. Check this computer's network or proxy and try again",
@@ -25,7 +61,7 @@ export default {
25
61
  "已打开:{value1}": "Opened: {value1}",
26
62
  "AI CoDiscuss 讨论服务\n服务目录:{value1}\n已登记 {value2} 个房间\nCtrl+C 停止服务\n": "AI CoDiscuss discussion service\nService folder: {value1}\n{value2} rooms registered\nCtrl+C to stop the service\n",
27
63
  "尚未登记房间;可在另一终端运行 codiscuss service add --config FILE。\n": "No rooms registered yet. Run codiscuss service add --config FILE in another terminal.\n",
28
- "用法:codiscuss admin <命令> [参数](与管理面板的操作一一对应;除启动与退出外,需管理面板正在运行)\n需要管理员权限的步骤(建或删 Windows 用户),在管理员终端或管理员的 SSH 会话里直接执行;否则在电脑桌面上弹出确认。\n\n启动与退出(不需要面板在运行)\n start 启动共议:服务、管理面板与任务栏图标、登录入口与隧道(在桌面会话里启动)\n stop 彻底退出:管理面板与图标、登录入口、隧道、共议服务;托管账号的实例照常运行\n restart stop 后 start\n update [check] 检查更新;不带 check 时安装最新版(面板未运行时先启动)并等待每一步结果\n\n本机\n status [--full] 概览:服务、版本、开机自启、登录入口、托管账号;--full 输出面板的完整状态\n service start|stop|restart 只启停共议服务(网站与讨论服务)\n autostart on|off 登录 Windows 时自动启动\n\n管理员入口\n site status 本地网页与线上网站的地址\n site connect <接入码|站点> [绑定令牌] 绑定线上网站(管理员外出、邀请外部专家用);在部署该网站的电脑上只填站点即可\n site disconnect 解绑线上网站,已配对的设备不能再连到这台电脑\n\n登录入口与访问方式(需打开托管管理)\n entry start|stop 启动或停止登录入口\n entry open|close relay|tunnel 开启或关闭访问方式:线上网站 | 自有域名,两种可同时开启\n entry join <接入码> 用接入码接入线上站点并开启线上网站\n entry code [--config <wrangler.jsonc>] [--site <地址>] 在部署线上站点的电脑上生成接入码(不填用上次的)\n entry tunnel <域名> [隧道名] 设置自有域名(Cloudflare 隧道),输出授权链接;域名须已托管在 Cloudflare\n entry tunnel status 查看自有域名设置的进度\n runtime sync 同步隔离账号的程序副本\n drives restrict 只允许隔离账号用系统盘:其他固定磁盘对它们的 Windows 用户拒绝访问(需管理员权限,之后重启它们的实例)\n\n托管账号\n account list\n account add <名> [--no-isolate] [--no-start] 创建、隔离、初始化 AI 环境、开启入口保护、启动;输出一次性密码。\n 中途失败时解决后重新执行同一命令,从缺少的步骤接着做\n account start|stop|disable|enable|remove|password <名>\n account isolate|unisolate|protect|unprotect <名>\n\n命令行登录(目标 owner 为管理员自己,否则为托管账号名)\n login status <目标> 各程序的登录状态,以及每个程序可用的登录方式\n login set <目标> <claude|codex> <方式> --set 字段=值 ... 如 login set alice claude setup_token --set token=sk-ant-oat01-…\n login start <目标> <程序> <方式> 浏览器登录:输出链接,之后用 login submit 提交授权码或回调地址\n login submit <作业> <文本> / login progress <作业> / login cancel <作业>\n logout <目标> <程序>\n\nAPI 密钥、技能、工作流、系统提示词(目标同上)\n key list <目标> / key add <目标> --base-url <地址> --key <密钥> / key remove <目标> <编号>\n skill library / skill import <文件夹或.zip> / skill delete <名>\n skill list <目标> / skill install <目标> <名>... / skill remove <目标> <名>...\n workflow list <目标> / workflow install <目标>\n prompt get <目标> / prompt set <目标> --file <文件> [--group <键>] 管理员的提示词按组保存(见 prompt get)\n prompt default get / prompt default set --file <文件> 新托管账号的默认系统提示词\n\n结果以 JSON 输出。--data 指定管理员服务目录(默认 ~/.codiscuss)。\n": "Usage: codiscuss admin <command> [arguments] (matches admin panel actions; the panel must be running except for start and stop)\nSteps requiring administrator rights (creating or deleting Windows users) run directly in an administrator terminal or administrator SSH session. Otherwise, approve the prompt on the computer's desktop.\n\nStart and exit (panel need not be running)\n start Start CoDiscuss: service, panel and tray icon, sign-in entry and tunnel (in the desktop session)\n stop Exit panel and tray icon, sign-in entry, tunnel and service; hosted instances keep running\n restart Run stop, then start\n update [check] Check for updates; omit check to install the latest version and wait for results (starts the panel if needed)\n\nLocal\n status [--full] Show service, version, startup, sign-in entry and hosted accounts; --full returns full panel state\n service start|stop|restart Start or stop only the CoDiscuss service (site and discussion service)\n autostart on|off Start automatically at Windows sign-in\n\nAdministrator entry\n site status Addresses of the local page and the online site\n site connect <access code|site> [token] Bind an online site (for using it away from this computer and inviting external experts); on the computer that deployed it, the site alone is enough\n site disconnect Unbind the online site; paired devices can no longer reach this computer\n\nSign-in entry and access methods (hosting must be enabled)\n entry start|stop Start or stop the sign-in entry\n entry open|close relay|tunnel Turn an access method on or off: online site | own domain; both can be on\n entry join <code> Connect to an online site with an access code and turn on the online site\n entry code [--config <wrangler.jsonc>] [--site <address>] Generate an access code on the deployment computer (defaults to last settings)\n entry tunnel <domain> [tunnel-name] Configure a Cloudflare Tunnel and show the authorization link; domain must be hosted on Cloudflare\n entry tunnel status Show domain setup progress\n runtime sync Sync program copies for isolated accounts\n drives restrict Keep isolated accounts on the system drive: other fixed drives deny their Windows users (needs administrator rights; restart their instances afterwards)\n\nHosted accounts\n account list\n account add <name> [--no-isolate] [--no-start] Create, isolate, initialize AI environment, protect and start; show password once\n On failure, fix the cause and rerun the same command to resume missing steps\n account start|stop|disable|enable|remove|password <name>\n account isolate|unisolate|protect|unprotect <name>\n\nCLI sign-ins (target owner is the admin; otherwise use a hosted account name)\n login status <target> Show each app's sign-in status and available methods\n login set <target> <claude|codex> <method> --set field=value ... e.g. login set alice claude setup_token --set token=sk-ant-oat01-…\n login start <target> <app> <method> Browser sign-in: show a link; use login submit for the authorization code or callback URL\n login submit <job> <text> / login progress <job> / login cancel <job>\n logout <target> <app>\n\nAPI keys, skills, workflows and system prompts (same target convention)\n key list <target> / key add <target> --base-url <address> --key <key> / key remove <target> <id>\n skill library / skill import <folder-or.zip> / skill delete <name>\n skill list <target> / skill install <target> <name>... / skill remove <target> <name>...\n workflow list <target> / workflow install <target>\n prompt get <target> / prompt set <target> --file <file> [--group <key>] Admin prompts are saved by group (see prompt get)\n prompt default get / prompt default set --file <file> Default system prompt for new hosted accounts\n\nResults are JSON. --data sets the admin service folder (default ~/.codiscuss).\n",
64
+ "用法:codiscuss admin <命令> [参数](与管理面板的操作一一对应;除启动与退出外,需管理面板正在运行)\n需要管理员权限的步骤(建或删 Windows 用户),在管理员终端或管理员的 SSH 会话里直接执行;否则在电脑桌面上弹出确认。\n\n启动与退出(不需要面板在运行)\n start 启动共议:服务、管理面板与任务栏图标、登录入口与隧道(在桌面会话里启动)\n stop 彻底退出:管理面板与图标、登录入口、隧道、共议服务;托管账号的实例照常运行\n restart stop 后 start\n update [check] 检查更新;不带 check 时安装最新版(面板未运行时先启动)并等待每一步结果\n\n本机\n status [--full] 概览:服务、中转状态、版本、开机自启、登录入口、托管账号;--full 输出面板的完整状态\n service start|stop|restart 只启停共议服务(网站与讨论服务)\n autostart on|off 登录 Windows 时自动启动\n\n管理员入口\n site status 本地网页与线上网站的地址\n site connect <接入码|站点> [绑定令牌] 绑定线上网站(管理员外出、邀请外部专家用);在部署该网站的电脑上只填站点即可\n site disconnect 解绑线上网站,已配对的设备不能再连到这台电脑\n site reconnect 立即重连已绑定网站的中转\n\n登录入口与访问方式(需打开托管管理)\n entry start|stop 启动或停止登录入口\n entry open|close relay|tunnel 开启或关闭访问方式:线上网站 | 自有域名,两种可同时开启\n entry join <接入码> 用接入码接入线上站点并开启线上网站\n entry code [--config <wrangler.jsonc>] [--site <地址>] 在部署线上站点的电脑上生成接入码(不填用上次的)\n entry tunnel <域名> [隧道名] 设置自有域名(Cloudflare 隧道),输出授权链接;域名须已托管在 Cloudflare\n entry tunnel status 查看自有域名设置的进度\n runtime sync 同步隔离账号的程序副本\n drives restrict 只允许隔离账号用系统盘:其他固定磁盘对它们的 Windows 用户拒绝访问(需管理员权限,之后重启它们的实例)\n\n托管账号\n account list\n account add <名> [--no-isolate] [--no-start] 创建、隔离、初始化 AI 环境、开启入口保护、启动;输出一次性密码。\n 中途失败时解决后重新执行同一命令,从缺少的步骤接着做\n account start|stop|disable|enable|remove|password <名>\n account isolate|unisolate|protect|unprotect <名>\n\n命令行登录(目标 owner 为管理员自己,否则为托管账号名)\n login status <目标> 各程序的登录状态,以及每个程序可用的登录方式\n login set <目标> <claude|codex> <方式> --set 字段=值 ... 如 login set alice claude setup_token --set token=sk-ant-oat01-…\n login start <目标> <程序> <方式> 浏览器登录:输出链接,之后用 login submit 提交授权码或回调地址\n login submit <作业> <文本> / login progress <作业> / login cancel <作业>\n logout <目标> <程序>\n\nAPI 密钥、技能、工作流、系统提示词(目标同上)\n key list <目标> / key add <目标> --base-url <地址> --key <密钥> / key remove <目标> <编号>\n skill library / skill import <文件夹或.zip> / skill delete <名>\n skill list <目标> / skill install <目标> <名>... / skill remove <目标> <名>...\n workflow list <目标> / workflow install <目标> / workflow update <目标>\n prompt get <目标> / prompt set <目标> --file <文件> [--group <键>] 管理员的提示词按组保存(见 prompt get)\n prompt default get / prompt default set --file <文件> 新托管账号的默认系统提示词\n\n结果以 JSON 输出。--data 指定管理员服务目录(默认 ~/.codiscuss)。\n": "Usage: codiscuss admin <command> [arguments] (matches admin panel actions; the panel must be running except for start and stop)\nSteps requiring administrator rights (creating or deleting Windows users) run directly in an administrator terminal or administrator SSH session. Otherwise, approve the prompt on the computer's desktop.\n\nStart and exit (panel need not be running)\n start Start CoDiscuss: service, panel and tray icon, sign-in entry and tunnel (in the desktop session)\n stop Exit panel and tray icon, sign-in entry, tunnel and service; hosted instances keep running\n restart Run stop, then start\n update [check] Check for updates; omit check to install the latest version and wait for results (starts the panel if needed)\n\nLocal\n status [--full] Show service, relay health, version, startup, sign-in entry and hosted accounts; --full returns full panel state\n service start|stop|restart Start or stop only the CoDiscuss service (site and discussion service)\n autostart on|off Start automatically at Windows sign-in\n\nAdministrator entry\n site status Addresses of the local page and the online site\n site connect <access code|site> [token] Bind an online site (for using it away from this computer and inviting external experts); on the computer that deployed it, the site alone is enough\n site disconnect Unbind the online site; paired devices can no longer reach this computer\n site reconnect Reconnect the relay to the bound online site now\n\nSign-in entry and access methods (hosting must be enabled)\n entry start|stop Start or stop the sign-in entry\n entry open|close relay|tunnel Turn an access method on or off: online site | own domain; both can be on\n entry join <code> Connect to an online site with an access code and turn on the online site\n entry code [--config <wrangler.jsonc>] [--site <address>] Generate an access code on the deployment computer (defaults to last settings)\n entry tunnel <domain> [tunnel-name] Configure a Cloudflare Tunnel and show the authorization link; domain must be hosted on Cloudflare\n entry tunnel status Show domain setup progress\n runtime sync Sync program copies for isolated accounts\n drives restrict Keep isolated accounts on the system drive: other fixed drives deny their Windows users (needs administrator rights; restart their instances afterwards)\n\nHosted accounts\n account list\n account add <name> [--no-isolate] [--no-start] Create, isolate, initialize AI environment, protect and start; show password once\n On failure, fix the cause and rerun the same command to resume missing steps\n account start|stop|disable|enable|remove|password <name>\n account isolate|unisolate|protect|unprotect <name>\n\nCLI sign-ins (target owner is the admin; otherwise use a hosted account name)\n login status <target> Show each app's sign-in status and available methods\n login set <target> <claude|codex> <method> --set field=value ... e.g. login set alice claude setup_token --set token=sk-ant-oat01-…\n login start <target> <app> <method> Browser sign-in: show a link; use login submit for the authorization code or callback URL\n login submit <job> <text> / login progress <job> / login cancel <job>\n logout <target> <app>\n\nAPI keys, skills, workflows and system prompts (same target convention)\n key list <target> / key add <target> --base-url <address> --key <key> / key remove <target> <id>\n skill library / skill import <folder-or.zip> / skill delete <name>\n skill list <target> / skill install <target> <name>... / skill remove <target> <name>...\n workflow list <target> / workflow install <target> / workflow update <target>\n prompt get <target> / prompt set <target> --file <file> [--group <key>] Admin prompts are saved by group (see prompt get)\n prompt default get / prompt default set --file <file> Default system prompt for new hosted accounts\n\nResults are JSON. --data sets the admin service folder (default ~/.codiscuss).\n",
29
65
  "管理面板没有在运行:在这台电脑的桌面上运行 codiscuss panel open,或从任务栏图标打开": "The admin panel is not running. Run codiscuss panel open on this computer's desktop, or open it from the tray icon.",
30
66
  "管理面板没有响应:在这台电脑的桌面上运行 codiscuss panel open": "The admin panel did not respond. Run codiscuss panel open on this computer's desktop.",
31
67
  "管理面板拒绝了钥匙(面板可能刚重启):稍后重试": "The admin panel rejected the key (it may have just restarted). Try again shortly.",
@@ -376,6 +412,8 @@ export default {
376
412
  "等待 Cloudflare 授权": "Wait for Cloudflare authorization",
377
413
  "即将打开浏览器:登录 Cloudflare,选择 {value1} 并点 Authorize,完成后回到这里": "Opening the browser: sign in to Cloudflare, select {value1} and click Authorize, then return here",
378
414
  "Cloudflare 授权没有完成,重新开始即可再试": "Cloudflare authorization incomplete; start again to retry",
415
+ "Cloudflare 授权的是另一个域名,记录被建成了 {value1}(可在 Cloudflare 删除);需要为 {value2} 重新授权": "The Cloudflare authorization covers another domain, so the record was created as {value1} (you can delete it in Cloudflare); authorize again for {value2}",
416
+ "授权的仍不是 {value1} 所在的域名,记录被建成了 {value2}:重新开始,在浏览器里选对域名": "The authorization still does not cover the domain of {value1}; the record was created as {value2}. Start again and pick the right domain in the browser",
379
417
  "建立隧道": "Create tunnel",
380
418
  "隧道 {value1} 建了却读不到,重新运行即可": "Tunnel {value1} was created but cannot be read; rerun to retry",
381
419
  "找不到隧道凭据 {value1}:这条隧道可能建在别的电脑上,换一个 --tunnel-name 重新运行": "Tunnel credentials not found: {value1}. The tunnel may be on another computer; rerun with a different --tunnel-name.",
@@ -0,0 +1,78 @@
1
+ /** The admin panel's bounded restart policy for hosted instances. Times in the journal are Unix milliseconds. */
2
+ import { appendFileSync, readFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { atomic_json } from './files.mjs';
5
+ import { t } from './i18n.mjs';
6
+
7
+ const WINDOW_MS = 600_000, BASE_DELAY_MS = 60_000, MAX_ATTEMPTS = 3;
8
+ const JOURNAL = 'instance-recovery.json';
9
+ const refused = () => ({ template: '实例端口拒绝连接', params: {} });
10
+
11
+ function read(path) {
12
+ try { return JSON.parse(readFileSync(path, 'utf8')); }
13
+ catch (error) { if (error.code === 'ENOENT') return {}; throw error; }
14
+ }
15
+ function save(path, name, row) {
16
+ const records = read(path);
17
+ if (row) records[name] = row;
18
+ else delete records[name];
19
+ atomic_json(path, records);
20
+ }
21
+ function log(data, name, at, message) {
22
+ appendFileSync(join(data, 'admin-panel.log'), `${new Date(at).toISOString()} [${name}] ${message}\n`, { mode: 0o600 });
23
+ }
24
+
25
+ /** Track one in-flight operation per account and keep restart budgets across panel restarts. */
26
+ export function instance_recovery(data, { wanted, probe, start, on_block, now = Date.now }) {
27
+ const path = join(data, JOURNAL), pending = new Map(), manual = new Map();
28
+ async function inspect(name) {
29
+ const port = wanted(name), row = read(path)[name] || {};
30
+ if (!port) return;
31
+ if (row.blocked) { on_block?.(name); return; }
32
+ if (await probe(port) !== 'down' || manual.has(name) || wanted(name) !== port) return;
33
+ const at = now(), attempts = (row.attempts || []).filter(time => at - time < WINDOW_MS);
34
+ if (attempts.length >= MAX_ATTEMPTS) {
35
+ save(path, name, { ...row, blocked: true, error: refused() });
36
+ log(data, name, now(), t('实例再次退出,自动重启已达上限。'));
37
+ on_block?.(name);
38
+ return;
39
+ }
40
+ if (attempts.length && at - attempts.at(-1) < BASE_DELAY_MS * 2 ** (attempts.length - 1)) return;
41
+ attempts.push(at);
42
+ const attempt = { attempts, at, reason: refused(), result: 'starting', blocked: false };
43
+ save(path, name, attempt);
44
+ log(data, name, now(), t('实例端口拒绝连接,正在自动重启(第 {count} 次)。', { count: attempts.length }));
45
+ try {
46
+ await start(name);
47
+ attempt.result = 'started';
48
+ } catch (error) {
49
+ attempt.error = error.error_text || { template: error.message, params: {} };
50
+ attempt.result = 'failed';
51
+ attempt.blocked = attempts.length === MAX_ATTEMPTS;
52
+ }
53
+ save(path, name, attempt);
54
+ if (attempt.blocked) on_block?.(name);
55
+ log(data, name, now(), attempt.error ? t('自动重启失败:{reason}', { reason: t(attempt.error.template, attempt.error.params) }) : t('实例已自动重启。'));
56
+ }
57
+ return {
58
+ status() { return read(path); },
59
+ check(name) {
60
+ if (!pending.has(name) && !manual.has(name)) {
61
+ pending.set(name, inspect(name).finally(() => pending.delete(name)));
62
+ }
63
+ return pending.get(name);
64
+ },
65
+ manage(name, action, run) {
66
+ const preceding = manual.get(name) || pending.get(name);
67
+ const operation = Promise.resolve(preceding).catch(() => {}).then(async () => {
68
+ const previous = read(path)[name];
69
+ if (['start', 'stop'].includes(action) && previous) save(path, name, { ...previous, attempts: [], blocked: false });
70
+ const result = await run();
71
+ if (action === 'remove') save(path, name, null);
72
+ return result;
73
+ }).finally(() => { if (manual.get(name) === operation) manual.delete(name); });
74
+ manual.set(name, operation);
75
+ return operation;
76
+ },
77
+ };
78
+ }
@@ -649,7 +649,12 @@ exit $LASTEXITCODE
649
649
  'ok'`);
650
650
  }
651
651
 
652
- /** Keep a stopped instance stopped when the computer starts again (its supervisor is stopped separately). */
652
+ /** Whether the owner requested that this isolated instance keep running. */
653
+ export function instance_flag_set(account) {
654
+ return existsSync(join(SHARED_ROOT, 'keys', account, RUN_FLAG));
655
+ }
656
+
657
+ /** Withdraw the owner's request to run this isolated instance. */
653
658
  export function clear_instance_flag(account) {
654
659
  rmSync(join(SHARED_ROOT, 'keys', account, RUN_FLAG), { force: true });
655
660
  }