@zhin.js/host-http 1.1.13 → 1.1.15

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.
@@ -1,10 +1,11 @@
1
1
  import type { AuthScope } from './token-registry.js';
2
2
  import type { DatabaseHostConsole } from '@zhin.js/plugin-runtime';
3
3
  import {
4
+ CONFIG_PATCH_LIMITS,
4
5
  CONFIG_RPC,
5
- ENDPOINT_RPC,
6
6
  type ConsoleConfigPatchRequest,
7
7
  type ConsoleConfigPatchResult,
8
+ type ConsoleConfigProjectPatchResult,
8
9
  type ConsoleConfigSource,
9
10
  type ConsoleConfigExplanation,
10
11
  type ConsoleEndpointSummary,
@@ -12,6 +13,13 @@ import {
12
13
  } from '@zhin.js/console-protocol';
13
14
  import { dispatchExtendedConsoleRpc, type ConsoleRpcExtendedCtx } from './console-rpc-extended/index.js';
14
15
  import { dispatchPluginConsoleRpc } from './console-plugin-rpc.js';
16
+ import {
17
+ configurationSaveMessage,
18
+ dispatchHostResourceConsoleRpc,
19
+ invalidProjectPatchOperations,
20
+ } from './console-rpc-handlers.js';
21
+
22
+ export { isDemoHttpAllowed } from './console-rpc-handlers.js';
15
23
 
16
24
  /**
17
25
  * Console RPC 请求结构:未锚定 endpoint 的会话地址(结构对齐
@@ -28,26 +36,6 @@ export interface ConversationAddress {
28
36
  readonly threadId?: string;
29
37
  }
30
38
 
31
- /** Canonical Console wire fields → runtime conversation address. */
32
- function wireConversation(
33
- channelType: string,
34
- channelId: string,
35
- parent: unknown,
36
- ): ConversationAddress {
37
- const kind: ConversationAddress['kind'] =
38
- channelType === 'group' || channelType === 'channel' ? channelType : 'private';
39
- const wire = parent && typeof parent === 'object'
40
- ? parent as { readonly type?: unknown; readonly id?: unknown }
41
- : undefined;
42
- const parentKind = wire?.type === 'group' || wire?.type === 'channel' ? wire.type : undefined;
43
- const parentId = typeof wire?.id === 'string' && wire.id ? wire.id : undefined;
44
- return {
45
- kind,
46
- id: channelId,
47
- ...(parentKind && parentId ? { parent: { kind: parentKind, id: parentId } } : {}),
48
- };
49
- }
50
-
51
39
  export type RuntimeConsoleRpcMessage = {
52
40
  readonly type?: unknown;
53
41
  readonly requestId?: unknown;
@@ -192,17 +180,22 @@ export type RuntimeConsoleRpcContext = {
192
180
  replaceConfigSource?(
193
181
  source: string,
194
182
  expectedRevision: string,
195
- ): Promise<{ readonly revision: string; readonly restartRequired: boolean }>;
183
+ ): Promise<{ readonly revision: string; readonly restartRequired: boolean } & import('@zhin.js/console-protocol').ConsoleConfigApplicationStatus>;
196
184
  /**
197
185
  * Full-scope write: set `document[pluginName] = data` and persist.
198
186
  * Returns whether a process restart is required.
199
187
  */
200
- setConfigKey?(pluginName: string, data: unknown): Promise<{ restartRequired: boolean }>;
188
+ setConfigKey?(pluginName: string, data: unknown): Promise<{ restartRequired: boolean } & import('@zhin.js/console-protocol').ConsoleConfigApplicationStatus>;
201
189
  /**
202
190
  * Full-scope, path-allowlisted and revision-checked write (`config:patch`).
203
191
  * Scope and schema checks belong to the implementation; scope violations throw.
204
192
  */
205
193
  patchConfig?(request: ConsoleConfigPatchRequest): Promise<ConsoleConfigPatchResult>;
194
+ /** Full-scope, revision-checked project administration, distinct from page allowlists. */
195
+ patchProjectConfig?(request: Omit<ConsoleConfigPatchRequest, 'instanceKey'>): Promise<ConsoleConfigProjectPatchResult>;
196
+ /** Full-scope project read (`config:get-project`); masked unless `reveal`. */
197
+ readProjectConfig?(request: import('@zhin.js/console-protocol').ConsoleConfigProjectReadRequest): Promise<import('@zhin.js/console-protocol').ConsoleConfigProjectRead>;
198
+ applyConfig?(expectedRevision: string): Promise<import('@zhin.js/console-protocol').ConsoleConfigApplyResult>;
206
199
  /** Persist a declared child Plugin lifecycle state. Takes effect after restart. */
207
200
  setPluginEnabled?(
208
201
  instanceKey: string,
@@ -427,6 +420,22 @@ export async function dispatchRuntimeConsoleRpc(
427
420
  }
428
421
  return payloads;
429
422
  }
423
+ case CONFIG_RPC.APPLY: {
424
+ if (ctx.authScope !== 'full') { emit({ requestId, error: 'Full Console scope is required' }); return payloads; }
425
+ if (typeof message.expectedRevision !== 'string' || !/^[a-f0-9]{64}$/u.test(message.expectedRevision)) {
426
+ emit({ requestId, error: 'expectedRevision is required' }); return payloads;
427
+ }
428
+ if (!ctx.applyConfig) { emit({ requestId, error: 'Config application is not configured' }); return payloads; }
429
+ try {
430
+ const result = await ctx.applyConfig(message.expectedRevision);
431
+ emit({ requestId, data: result });
432
+ } catch {
433
+ // Source reads can fail before an operation is admitted. Do not echo a
434
+ // YAML parser's source excerpt or turn unavailable evidence into success.
435
+ emit({ requestId, error: 'Configuration application is unavailable; read the source and runtime status before retrying' });
436
+ }
437
+ return payloads;
438
+ }
430
439
  case CONFIG_RPC.REPLACE_SOURCE: {
431
440
  try {
432
441
  const source = message.source;
@@ -450,9 +459,7 @@ export async function dispatchRuntimeConsoleRpc(
450
459
  data: {
451
460
  success: true,
452
461
  ...result,
453
- message: result.restartRequired
454
- ? '配置已保存,需重启进程才能生效'
455
- : '配置已保存',
462
+ message: configurationSaveMessage(result),
456
463
  },
457
464
  });
458
465
  } catch (error) {
@@ -463,9 +470,33 @@ export async function dispatchRuntimeConsoleRpc(
463
470
  }
464
471
  return payloads;
465
472
  }
473
+ case CONFIG_RPC.GET_PROJECT: {
474
+ if (ctx.authScope !== 'full') { emit({ requestId, error: 'Full scope required' }); return payloads; }
475
+ const { path, reveal } = message;
476
+ if (path !== undefined && (!Array.isArray(path) || path.length > CONFIG_PATCH_LIMITS.maxPathDepth
477
+ || path.some(segment => typeof segment !== 'string' || !segment || segment.length > CONFIG_PATCH_LIMITS.maxSegmentLength))) {
478
+ emit({ requestId, error: 'path 必须是非空字符串数组' });
479
+ return payloads;
480
+ }
481
+ if (reveal !== undefined && typeof reveal !== 'boolean') { emit({ requestId, error: 'reveal 必须是布尔值' }); return payloads; }
482
+ if (!ctx.readProjectConfig) { emit({ requestId, error: 'Config project read is not configured' }); return payloads; }
483
+ try {
484
+ emit({ requestId, data: await ctx.readProjectConfig({ path: (path ?? []) as string[], reveal: reveal === true }) });
485
+ } catch {
486
+ // Parser/IO messages can quote document source (and therefore secrets): never echo them.
487
+ emit({ requestId, error: 'Configuration read is unavailable; read the project file locally to diagnose it' });
488
+ }
489
+ return payloads;
490
+ }
491
+ case CONFIG_RPC.PATCH_PROJECT:
466
492
  case CONFIG_RPC.PATCH: {
467
493
  if (ctx.authScope !== 'full') { emit({ requestId, error: 'Full scope required' }); return payloads; }
494
+ const projectPatch = message.type === CONFIG_RPC.PATCH_PROJECT;
468
495
  const { instanceKey, expectedRevision, patches } = message;
496
+ if (projectPatch && instanceKey !== undefined) {
497
+ emit({ requestId, error: 'Project patches must not specify instanceKey' });
498
+ return payloads;
499
+ }
469
500
  if (instanceKey !== undefined && (typeof instanceKey !== 'string' || !instanceKey || instanceKey.length > 128)) {
470
501
  emit({ requestId, error: 'instanceKey 必须是插件实例名,或省略以使用 Host 白名单' });
471
502
  return payloads;
@@ -478,31 +509,41 @@ export async function dispatchRuntimeConsoleRpc(
478
509
  emit({ requestId, error: 'patches 必须是数组' });
479
510
  return payloads;
480
511
  }
481
- if (!ctx.patchConfig) {
512
+ if (projectPatch) {
513
+ const invalid = invalidProjectPatchOperations(patches);
514
+ if (invalid) { emit({ requestId, error: invalid }); return payloads; }
515
+ }
516
+ const patch = projectPatch ? ctx.patchProjectConfig : ctx.patchConfig;
517
+ if (!patch) {
482
518
  emit({ requestId, error: 'Config patch is not configured' });
483
519
  return payloads;
484
520
  }
521
+ let result: Awaited<ReturnType<typeof patch>>;
485
522
  try {
486
- const result = await ctx.patchConfig({
523
+ result = await patch.call(ctx, {
487
524
  ...(instanceKey === undefined ? {} : { instanceKey }),
488
525
  expectedRevision,
489
526
  patches,
490
527
  });
491
- if (result.status === 'saved') {
528
+ } catch (error) {
529
+ emit({
530
+ requestId,
531
+ error: `Failed to patch config: ${error instanceof Error ? error.message : String(error)}`,
532
+ });
533
+ return payloads;
534
+ }
535
+ if (result.status === 'saved') {
536
+ // The write has committed: a notification failure must not turn the receipt into a rejection.
537
+ try {
492
538
  ctx.publishEvent?.('config:updated', {
493
539
  pluginName: instanceKey ?? null,
494
540
  keys: [...new Set(result.paths.map(path => path[0]))],
495
541
  paths: result.paths,
496
542
  revision: result.revision,
497
543
  });
498
- }
499
- emit({ requestId, data: result });
500
- } catch (error) {
501
- emit({
502
- requestId,
503
- error: `Failed to patch config: ${error instanceof Error ? error.message : String(error)}`,
504
- });
544
+ } catch { /* subscribers resynchronise from the next read */ }
505
545
  }
546
+ emit({ requestId, data: result });
506
547
  return payloads;
507
548
  }
508
549
  case CONFIG_RPC.SET: {
@@ -538,10 +579,9 @@ export async function dispatchRuntimeConsoleRpc(
538
579
  requestId,
539
580
  data: {
540
581
  success: true,
582
+ ...result,
541
583
  reloaded: false,
542
- message: result.restartRequired
543
- ? '配置已保存,需重启进程才能生效'
544
- : '配置已保存',
584
+ message: configurationSaveMessage(result),
545
585
  },
546
586
  });
547
587
  } catch (error) {
@@ -552,465 +592,10 @@ export async function dispatchRuntimeConsoleRpc(
552
592
  }
553
593
  return payloads;
554
594
  }
555
- case 'files:tree': {
556
- try {
557
- const tree = ctx.listProjectFiles ? await ctx.listProjectFiles() : [];
558
- emit({ requestId, data: { tree } });
559
- } catch (error) {
560
- emit({
561
- requestId,
562
- error: `Failed to build file tree: ${error instanceof Error ? error.message : String(error)}`,
563
- });
564
- }
565
- return payloads;
566
- }
567
- case 'files:read': {
568
- try {
569
- const filePath = String(message.filePath ?? '');
570
- if (!filePath) {
571
- emit({ requestId, error: 'filePath is required' });
572
- return payloads;
573
- }
574
- if (!ctx.readProjectFile) {
575
- emit({ requestId, error: 'File read is not configured' });
576
- return payloads;
577
- }
578
- const file = await ctx.readProjectFile(filePath);
579
- emit({ requestId, data: file });
580
- } catch (error) {
581
- emit({
582
- requestId,
583
- error: `Failed to read file: ${error instanceof Error ? error.message : String(error)}`,
584
- });
585
- }
586
- return payloads;
587
- }
588
- case 'files:save': {
589
- try {
590
- const filePath = String(message.filePath ?? '');
591
- const content = message.content;
592
- if (!filePath) {
593
- emit({ requestId, error: 'filePath is required' });
594
- return payloads;
595
- }
596
- if (typeof content !== 'string') {
597
- emit({ requestId, error: 'content field is required' });
598
- return payloads;
599
- }
600
- if (!ctx.saveProjectFile) {
601
- emit({ requestId, error: 'File write is not configured' });
602
- return payloads;
603
- }
604
- await ctx.saveProjectFile(filePath, content);
605
- emit({ requestId, data: { success: true, message: `文件已保存: ${filePath}` } });
606
- } catch (error) {
607
- emit({
608
- requestId,
609
- error: `Failed to save file: ${error instanceof Error ? error.message : String(error)}`,
610
- });
611
- }
612
- return payloads;
613
- }
614
- case 'env:list': {
615
- try {
616
- const files = ctx.listEnvFiles ? await ctx.listEnvFiles() : [];
617
- emit({ requestId, data: { files } });
618
- } catch (error) {
619
- emit({
620
- requestId,
621
- error: `Failed to list env files: ${error instanceof Error ? error.message : String(error)}`,
622
- });
623
- }
624
- return payloads;
625
- }
626
- case 'env:get': {
627
- try {
628
- const filename = String(message.filename ?? '');
629
- if (!filename) {
630
- emit({ requestId, error: 'filename is required' });
631
- return payloads;
632
- }
633
- if (!ctx.readEnvFile) {
634
- emit({ requestId, error: 'Env read is not configured' });
635
- return payloads;
636
- }
637
- const content = await ctx.readEnvFile(filename);
638
- emit({ requestId, data: { content } });
639
- } catch (error) {
640
- emit({
641
- requestId,
642
- error: `Failed to read env file: ${error instanceof Error ? error.message : String(error)}`,
643
- });
644
- }
645
- return payloads;
646
- }
647
- case 'env:save': {
648
- try {
649
- const filename = String(message.filename ?? '');
650
- const content = message.content;
651
- if (!filename) {
652
- emit({ requestId, error: 'filename is required' });
653
- return payloads;
654
- }
655
- if (typeof content !== 'string') {
656
- emit({ requestId, error: 'content field is required' });
657
- return payloads;
658
- }
659
- if (!ctx.writeEnvFile) {
660
- emit({ requestId, error: 'Env write is not configured' });
661
- return payloads;
662
- }
663
- await ctx.writeEnvFile(filename, content);
664
- emit({ requestId, data: { success: true, message: `环境文件已保存: ${filename}` } });
665
- } catch (error) {
666
- emit({
667
- requestId,
668
- error: `Failed to save env file: ${error instanceof Error ? error.message : String(error)}`,
669
- });
670
- }
671
- return payloads;
672
- }
673
- case 'schema:get': {
674
- try {
675
- const pluginName = typeof message.pluginName === 'string'
676
- ? message.pluginName
677
- : undefined;
678
- const schema = ctx.getSchema ? await ctx.getSchema(pluginName) : null;
679
- emit({ requestId, data: schema });
680
- } catch (error) {
681
- emit({
682
- requestId,
683
- error: `Failed to get schema: ${error instanceof Error ? error.message : String(error)}`,
684
- });
685
- }
686
- return payloads;
687
- }
688
- case 'schema:get-all': {
689
- try {
690
- const schemas = ctx.getAllSchemas ? await ctx.getAllSchemas() : {};
691
- emit({ requestId, data: schemas });
692
- } catch (error) {
693
- emit({
694
- requestId,
695
- error: `Failed to get all schemas: ${error instanceof Error ? error.message : String(error)}`,
696
- });
697
- }
698
- return payloads;
699
- }
700
- case 'db:info': {
701
- if (ctx.database) {
702
- emit({ requestId, data: ctx.database.info() });
703
- return payloads;
704
- }
705
- if (ctx.dbInfo) {
706
- try {
707
- emit({ requestId, data: await ctx.dbInfo() });
708
- } catch (error) {
709
- emit({
710
- requestId,
711
- error: error instanceof Error ? error.message : String(error),
712
- });
713
- }
595
+ default: {
596
+ if (await dispatchHostResourceConsoleRpc(type, message, ctx, requestId, payloads)) {
714
597
  return payloads;
715
598
  }
716
- emit({
717
- requestId,
718
- data: { dialect: null, connected: false, message: 'Database not configured on Plugin Runtime Host' },
719
- });
720
- return payloads;
721
- }
722
- case 'db:tables': {
723
- try {
724
- if (ctx.database) {
725
- emit({ requestId, data: { tables: ctx.database.tables() } });
726
- return payloads;
727
- }
728
- const tables = ctx.dbTables ? await ctx.dbTables() : [];
729
- emit({ requestId, data: tables });
730
- } catch (error) {
731
- emit({
732
- requestId,
733
- error: error instanceof Error ? error.message : String(error),
734
- });
735
- }
736
- return payloads;
737
- }
738
- case 'db:select': {
739
- const table = stringField(message, 'table');
740
- if (!table) return errorReply(payloads, requestId, 'table is required');
741
- const page = positiveInteger(message.page, 1);
742
- const pageSize = Math.min(positiveInteger(message.pageSize, 50), 500);
743
- const where = recordField(message.where);
744
- if (!ctx.database) {
745
- emit({ requestId, data: { rows: [], total: 0, page, pageSize } });
746
- return payloads;
747
- }
748
- try {
749
- emit({ requestId, data: await ctx.database.select(table, page, pageSize, where) });
750
- } catch (error) {
751
- emit({ requestId, error: `Failed to select: ${errorMessage(error)}` });
752
- }
753
- return payloads;
754
- }
755
- case 'db:insert': {
756
- if (!ctx.database) return errorReply(payloads, requestId, 'Database RPC is not available on Plugin Runtime Host');
757
- const table = stringField(message, 'table');
758
- const row = recordField(message.row);
759
- if (!table || !row) return errorReply(payloads, requestId, 'table and row are required');
760
- try {
761
- await ctx.database.insert(table, row);
762
- emit({ requestId, data: { success: true } });
763
- } catch (error) {
764
- emit({ requestId, error: `Failed to insert: ${errorMessage(error)}` });
765
- }
766
- return payloads;
767
- }
768
- case 'db:update': {
769
- if (!ctx.database) return errorReply(payloads, requestId, 'Database RPC is not available on Plugin Runtime Host');
770
- const table = stringField(message, 'table');
771
- const row = recordField(message.row);
772
- const where = recordField(message.where);
773
- if (!table || !row || !where) {
774
- return errorReply(payloads, requestId, 'table, row, and where are required');
775
- }
776
- try {
777
- const affected = await ctx.database.update(table, row, where);
778
- emit({ requestId, data: { success: true, affected } });
779
- } catch (error) {
780
- emit({ requestId, error: `Failed to update: ${errorMessage(error)}` });
781
- }
782
- return payloads;
783
- }
784
- case 'db:delete': {
785
- if (!ctx.database) return errorReply(payloads, requestId, 'Database RPC is not available on Plugin Runtime Host');
786
- const table = stringField(message, 'table');
787
- const where = recordField(message.where);
788
- if (!table || !where) return errorReply(payloads, requestId, 'table and where are required');
789
- try {
790
- const deleted = await ctx.database.delete(table, where);
791
- emit({ requestId, data: { success: true, deleted } });
792
- } catch (error) {
793
- emit({ requestId, error: `Failed to delete: ${errorMessage(error)}` });
794
- }
795
- return payloads;
796
- }
797
- case 'db:drop-table': {
798
- if (!ctx.database) return errorReply(payloads, requestId, 'Database RPC is not available on Plugin Runtime Host');
799
- const table = stringField(message, 'table');
800
- if (!table) return errorReply(payloads, requestId, 'table is required');
801
- try {
802
- await ctx.database.dropTable(table);
803
- emit({ requestId, data: { success: true } });
804
- } catch (error) {
805
- emit({ requestId, error: `Failed to drop table: ${errorMessage(error)}` });
806
- }
807
- return payloads;
808
- }
809
- case 'db:kv:get': {
810
- const table = stringField(message, 'table');
811
- const key = stringField(message, 'key');
812
- if (!table || !key) return errorReply(payloads, requestId, 'table and key are required');
813
- if (!ctx.database) {
814
- emit({ requestId, data: { key, value: null } });
815
- return payloads;
816
- }
817
- try {
818
- emit({ requestId, data: { key, value: await ctx.database.kvGet(table, key) } });
819
- } catch (error) {
820
- emit({ requestId, error: `Failed to get kv: ${errorMessage(error)}` });
821
- }
822
- return payloads;
823
- }
824
- case 'db:kv:set': {
825
- if (!ctx.database) return errorReply(payloads, requestId, 'Database RPC is not available on Plugin Runtime Host');
826
- const table = stringField(message, 'table');
827
- const key = stringField(message, 'key');
828
- if (!table || !key) return errorReply(payloads, requestId, 'table and key are required');
829
- try {
830
- const ttl = typeof message.ttl === 'number' && Number.isFinite(message.ttl)
831
- ? message.ttl
832
- : undefined;
833
- await ctx.database.kvSet(table, key, message.value, ttl);
834
- emit({ requestId, data: { success: true } });
835
- } catch (error) {
836
- emit({ requestId, error: `Failed to set kv: ${errorMessage(error)}` });
837
- }
838
- return payloads;
839
- }
840
- case 'db:kv:delete': {
841
- if (!ctx.database) return errorReply(payloads, requestId, 'Database RPC is not available on Plugin Runtime Host');
842
- const table = stringField(message, 'table');
843
- const key = stringField(message, 'key');
844
- if (!table || !key) return errorReply(payloads, requestId, 'table and key are required');
845
- try {
846
- await ctx.database.kvDelete(table, key);
847
- emit({ requestId, data: { success: true } });
848
- } catch (error) {
849
- emit({ requestId, error: `Failed to delete kv: ${errorMessage(error)}` });
850
- }
851
- return payloads;
852
- }
853
- case 'db:kv:entries': {
854
- const table = stringField(message, 'table');
855
- if (!table) return errorReply(payloads, requestId, 'table is required');
856
- if (!ctx.database) {
857
- emit({ requestId, data: { entries: [] } });
858
- return payloads;
859
- }
860
- try {
861
- emit({ requestId, data: { entries: await ctx.database.kvEntries(table) } });
862
- } catch (error) {
863
- emit({ requestId, error: `Failed to get entries: ${errorMessage(error)}` });
864
- }
865
- return payloads;
866
- }
867
- case 'endpoint.list': {
868
- try {
869
- const endpoints = ctx.listEndpoints ? await ctx.listEndpoints() : [];
870
- emit({ requestId, data: { endpoints } });
871
- } catch (error) {
872
- emit({
873
- requestId,
874
- error: error instanceof Error ? error.message : String(error),
875
- });
876
- }
877
- return payloads;
878
- }
879
- case 'endpoint.info': {
880
- try {
881
- const data = recordField(message.data) ?? message;
882
- const adapter = String(data.adapter ?? '');
883
- const endpointKey = String(data.endpointKey ?? '');
884
- if (!adapter || !endpointKey) {
885
- emit({ requestId, error: 'adapter and endpointKey are required' });
886
- return payloads;
887
- }
888
- if (!ctx.getEndpoint) {
889
- emit({ requestId, error: 'Endpoint registry is not configured' });
890
- return payloads;
891
- }
892
- const endpoint = await ctx.getEndpoint(adapter, endpointKey);
893
- if (!endpoint) {
894
- emit({ requestId, error: 'endpoint not found' });
895
- return payloads;
896
- }
897
- emit({ requestId, data: endpoint });
898
- } catch (error) {
899
- emit({
900
- requestId,
901
- error: error instanceof Error ? error.message : String(error),
902
- });
903
- }
904
- return payloads;
905
- }
906
- case ENDPOINT_RPC.TEST: {
907
- const data = recordField(message.data) ?? message;
908
- const adapter = stringField(data, 'adapter');
909
- const endpointKey = stringField(data, 'endpointKey');
910
- if (!adapter || !endpointKey) {
911
- emit({ requestId, error: 'adapter and endpointKey are required' });
912
- return payloads;
913
- }
914
- if (!ctx.getEndpoint) {
915
- emit({ requestId, error: 'Endpoint registry is not configured' });
916
- return payloads;
917
- }
918
- const startedAt = Date.now();
919
- try {
920
- const endpoint = await ctx.getEndpoint(adapter, endpointKey);
921
- if (!endpoint) {
922
- emit({ requestId, data: {
923
- reachable: false,
924
- connected: false,
925
- phase: 'unconfigured',
926
- latencyMs: Date.now() - startedAt,
927
- message: 'Endpoint 未注册到当前 generation',
928
- } });
929
- return payloads;
930
- }
931
- emit({ requestId, data: {
932
- reachable: endpoint.connected && endpoint.status === 'online',
933
- connected: endpoint.connected,
934
- status: endpoint.status,
935
- admitted: endpoint.admitted,
936
- transportState: endpoint.transportState,
937
- phase: endpoint.phase ?? (endpoint.connected ? 'online' : 'pending'),
938
- pendingLogin: endpoint.pendingLogin ?? false,
939
- latencyMs: Date.now() - startedAt,
940
- message: endpoint.connected
941
- ? 'Endpoint 已连接'
942
- : endpoint.pendingLogin
943
- ? 'Endpoint 等待登录操作'
944
- : 'Endpoint 当前离线',
945
- } });
946
- } catch (error) {
947
- emit({ requestId, data: {
948
- reachable: false,
949
- connected: false,
950
- phase: 'failed',
951
- latencyMs: Date.now() - startedAt,
952
- message: error instanceof Error ? error.message : String(error),
953
- } });
954
- }
955
- return payloads;
956
- }
957
- case 'endpoint.send_message': {
958
- try {
959
- const data = recordField(message.data) ?? message;
960
- const adapter = String(data.adapter ?? '');
961
- const endpointKey = String(data.endpointKey ?? '');
962
- const channelId = String(data.channelId ?? data.id ?? '');
963
- const channelType = String(data.channelType ?? data.type ?? '');
964
- const content = data.content;
965
- if (!adapter || !endpointKey || !channelId || !channelType || content === undefined) {
966
- emit({
967
- requestId,
968
- error: 'adapter, endpointKey, channelId, channelType, and content are required',
969
- });
970
- return payloads;
971
- }
972
- if (!ctx.sendEndpointMessage) {
973
- emit({ requestId, error: 'Endpoint send is not configured' });
974
- return payloads;
975
- }
976
- const result = await ctx.sendEndpointMessage({
977
- adapter,
978
- endpointKey,
979
- conversation: wireConversation(channelType, channelId, data.parent),
980
- content,
981
- });
982
- emit({ requestId, data: { messageId: result.messageId } });
983
- } catch (error) {
984
- emit({
985
- requestId,
986
- error: error instanceof Error ? error.message : String(error),
987
- });
988
- }
989
- return payloads;
990
- }
991
- case 'system:restart': {
992
- try {
993
- if (!ctx.requestRestart) {
994
- emit({ requestId, error: 'Process restart is not configured' });
995
- return payloads;
996
- }
997
- ctx.publishEvent?.('system:restarting', { timestamp: Date.now() });
998
- emit({ requestId, data: { success: true, message: '正在重启...' } });
999
- // Delay so the HTTP response can flush (parity with legacy host-api).
1000
- setTimeout(() => {
1001
- void Promise.resolve(ctx.requestRestart?.()).catch(() => {
1002
- /* restart is best-effort */
1003
- });
1004
- }, 500);
1005
- } catch (error) {
1006
- emit({
1007
- requestId,
1008
- error: error instanceof Error ? error.message : String(error),
1009
- });
1010
- }
1011
- return payloads;
1012
- }
1013
- default:
1014
599
  if (type.startsWith('db:')) {
1015
600
  emit({
1016
601
  requestId,
@@ -1020,65 +605,6 @@ export async function dispatchRuntimeConsoleRpc(
1020
605
  }
1021
606
  emit({ requestId, error: `Unknown RPC type: ${type || '<empty>'}` });
1022
607
  return payloads;
608
+ }
1023
609
  }
1024
610
  }
1025
-
1026
- function stringField(message: RuntimeConsoleRpcMessage, key: string): string {
1027
- const value = message[key];
1028
- return typeof value === 'string' ? value.trim() : '';
1029
- }
1030
-
1031
- function recordField(value: unknown): Record<string, unknown> | undefined {
1032
- return value && typeof value === 'object' && !Array.isArray(value)
1033
- ? value as Record<string, unknown>
1034
- : undefined;
1035
- }
1036
-
1037
- function positiveInteger(value: unknown, fallback: number): number {
1038
- const parsed = Number(value ?? fallback);
1039
- return Number.isInteger(parsed) && parsed > 0 ? parsed : fallback;
1040
- }
1041
-
1042
- function errorMessage(error: unknown): string {
1043
- return error instanceof Error ? error.message : String(error);
1044
- }
1045
-
1046
- function errorReply(
1047
- payloads: RuntimeConsoleRpcReply[],
1048
- requestId: number | string | undefined,
1049
- error: string,
1050
- ): RuntimeConsoleRpcReply[] {
1051
- payloads.push({ requestId, error });
1052
- return payloads;
1053
- }
1054
-
1055
- /** HTTP paths under apiBase that demo scope may call (ADR 0016). */
1056
- export function isDemoHttpAllowed(method: string, pathname: string, apiBase: string): boolean {
1057
- const normalizedBase = apiBase.replace(/\/$/u, '') || '/api';
1058
- const m = method.toUpperCase();
1059
- // These handlers require an authenticated principal and verify its bound personal owner.
1060
- if ((m === 'GET' || m === 'PUT') && (pathname === `${normalizedBase}/agent/personal-models`
1061
- || pathname === `${normalizedBase}/agent/personal-session`)) return true;
1062
- if (m === 'GET' && pathname === `${normalizedBase}/agent/personal-sessions`) return true;
1063
- if (m === 'GET' && pathname === `${normalizedBase}/events`) return true;
1064
- if (m === 'GET' && pathname === `${normalizedBase}/events/history`) return true;
1065
- if (m === 'GET' && DEMO_INTROSPECTION_PATHS.has(pathname.slice(normalizedBase.length))) return true;
1066
- if (m === 'POST' && pathname === `${normalizedBase}/console/request`) return true;
1067
- // Read-only dashboard / plugin inspection routes (legacy host-api parity).
1068
- if (m === 'GET' && pathname === `${normalizedBase}/system/status`) return true;
1069
- if (m === 'GET' && pathname === `${normalizedBase}/stats`) return true;
1070
- if (m === 'GET' && (pathname === `${normalizedBase}/plugins`
1071
- || pathname.startsWith(`${normalizedBase}/plugins/`))) return true;
1072
- return false;
1073
- }
1074
-
1075
- const DEMO_INTROSPECTION_PATHS: ReadonlySet<string> = new Set([
1076
- '/introspection/commands',
1077
- '/introspection/middlewares',
1078
- '/introspection/components',
1079
- '/introspection/endpoints',
1080
- '/introspection/bindings',
1081
- '/introspection/tools',
1082
- '/introspection/prompt-sections',
1083
- '/introspection/mcp',
1084
- ]);