@unson/brainbase-mcp 0.51.9 → 0.51.11

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.
@@ -9,9 +9,11 @@
9
9
  */
10
10
 
11
11
  import { districtTaskActors } from './world-placement.js';
12
+ import { exitHrefKind } from './world-exits.js';
12
13
 
13
14
  import {
14
15
  makeWorkspaceElement as el,
16
+ workspaceRailHead,
15
17
  workspaceRailBlock,
16
18
  workspaceDefinition,
17
19
  workspaceButton,
@@ -655,8 +657,11 @@ export function createPulsePanel(doc, { onWorld, onCity, onStreet, onSite, onEnt
655
657
  return {
656
658
  node,
657
659
  hide() { node.hidden = true; },
658
- /** The world: `world` from `worldPulse`; `connected` false when the host has no task store. */
659
- showWorld({ world, connected }) {
660
+ /**
661
+ * The world: `world` from `worldPulse`; `connected` false when the host has no task store; `agents`
662
+ * the line from `worldAgentPulseLine` (its own row with its source, never added to the businesses).
663
+ */
664
+ showWorld({ world, connected, agents = null }) {
660
665
  node.hidden = false;
661
666
  node.dataset.level = 'world';
662
667
  setCrumbs([{ text: '世界' }]);
@@ -680,6 +685,11 @@ export function createPulsePanel(doc, { onWorld, onCity, onStreet, onSite, onEnt
680
685
  }
681
686
  nodes.push(list, note('事業を選ぶと、その中の動きを見られます。'));
682
687
  }
688
+ if (agents) {
689
+ const line = el(doc, 'div', { className: `bb-world-pulse-agents is-${agents.tone}` });
690
+ line.append(el(doc, 'p', { className: 'bb-world-pulse-agents-count', text: agents.text }), el(doc, 'p', { className: 'bb-world-pulse-agents-source', text: agents.source }));
691
+ nodes.splice(1, 0, line);
692
+ }
683
693
  body.replaceChildren(...nodes);
684
694
  },
685
695
  /** A business: `pulse` from `districtPulse`, or `state` saying why its work is not shown. */
@@ -764,3 +774,263 @@ export function createPulsePanel(doc, { onWorld, onCity, onStreet, onSite, onEnt
764
774
  },
765
775
  };
766
776
  }
777
+
778
+ /*
779
+ * ---------------------------------------------------------------------------------------------
780
+ * AI agents on the world (story-world-agents-step1-v1, design item #707).
781
+ *
782
+ * A host may hand the world an execution-state projection of its AI agents (`world-agents.v1`, for
783
+ * example Orca run receipts). It is not Brainbase's judgment record: the agents never stand in the
784
+ * plaza, and every place they appear says where they came from. The world only draws what the host
785
+ * decided; it never infers a state, and anything it cannot confirm is said to be unconfirmed — never
786
+ * idle, never zero (ledger P9). The overview is quiet when everything is normal: needs_you is the
787
+ * strongest sign, blocked the second (another colour and shape), working is a low dot, idle melts
788
+ * into the scenery (the reverse of the district's running > waiting light, which suits one street
789
+ * but would bury the exceptions in an overview of many agents).
790
+ * ---------------------------------------------------------------------------------------------
791
+ */
792
+
793
+ export const WORLD_AGENTS_CONTRACT_VERSION = 'world-agents.v1';
794
+ /** The footer every agent detail carries: the projection is not the judgment record. */
795
+ export const WORLD_AGENT_SOURCE_TEXT = '出典: Orca 実行状態投影(Brainbase 判断記録とは別系統)';
796
+ const AGENT_STATE_KEYS = ['idle', 'working', 'needs_you', 'blocked', 'unconfirmed'];
797
+ const AGENT_FRESHNESS_KEYS = ['fresh', 'stale', 'unconfirmed'];
798
+
799
+ /**
800
+ * How each look is drawn over the whole world, strongest first. `light` is the emissive strength of the
801
+ * agent's sign (0: no light at all); `badge` the glyph on its board and `shape` the board's shape, so the
802
+ * two strong signs differ in colour and shape, not only in colour. `breathe` is a slow 3–4 s breath
803
+ * (never a blink), off under reduced motion.
804
+ */
805
+ export const WORLD_AGENT_LOOKS = Object.freeze({
806
+ needs_you: Object.freeze({ label: '要決裁', color: '#e8a10c', light: 1.8, badge: '?', shape: 'square', breathe: true, rank: 5 }),
807
+ blocked: Object.freeze({ label: '停止', color: '#d2462b', light: 1.3, badge: '!', shape: 'octagon', breathe: false, rank: 4 }),
808
+ working: Object.freeze({ label: '稼働中', color: '#3f9a87', light: 0.45, badge: null, shape: 'dot', breathe: false, rank: 3 }),
809
+ stale: Object.freeze({ label: '最新未確認', color: '#9aa1a4', light: 0, badge: null, shape: null, breathe: false, rank: 2 }),
810
+ idle: Object.freeze({ label: '待機中', color: '#c2c7c5', light: 0, badge: null, shape: null, breathe: false, rank: 1 }),
811
+ unconfirmed: Object.freeze({ label: '稼働未確認', color: '#9aa3a6', light: 0, badge: null, shape: 'dashed', breathe: false, rank: 0 }),
812
+ });
813
+
814
+ const agentText = (value) => (typeof value === 'string' && value.trim() ? value.trim() : null);
815
+ const agentCount = (value) => (Number.isInteger(value) && value >= 0 ? value : null);
816
+
817
+ function agentAgeMinutes(agent, checkedAt) {
818
+ if (Number.isFinite(agent?.age_sec) && agent.age_sec >= 0) return Math.floor(agent.age_sec / 60);
819
+ const observed = Date.parse(agent?.observed_at ?? '');
820
+ const checked = Date.parse(checkedAt ?? '');
821
+ if (Number.isFinite(observed) && Number.isFinite(checked) && checked >= observed) return Math.floor((checked - observed) / 60000);
822
+ return null;
823
+ }
824
+
825
+ /**
826
+ * The look of one agent from the state and freshness the host decided. A stale working (or idle) agent
827
+ * loses its light (it may have stopped); a stale needs_you or blocked keeps its strong sign with a
828
+ * freshness caution (missing it costs most); anything unconfirmed is drawn as unconfirmed, never idle.
829
+ */
830
+ export function worldAgentLook(agent) {
831
+ const state = AGENT_STATE_KEYS.includes(agent?.state) ? agent.state : 'unconfirmed';
832
+ if (state === 'unconfirmed') return { look: 'unconfirmed', caution: false };
833
+ // A freshness the contract does not know (a future value, a typo, missing) is not the host's explicit
834
+ // `stale` / `unconfirmed`: it fails closed to unconfirmed, never a strong sign counted as waiting.
835
+ if (!AGENT_FRESHNESS_KEYS.includes(agent?.freshness)) return { look: 'unconfirmed', caution: false };
836
+ const freshness = agent.freshness;
837
+ if (state === 'needs_you' || state === 'blocked') return { look: state, caution: freshness !== 'fresh' };
838
+ if (freshness === 'unconfirmed') return { look: 'unconfirmed', caution: false };
839
+ if (freshness === 'stale') return { look: 'stale', caution: false };
840
+ return { look: state, caution: false };
841
+ }
842
+
843
+ /**
844
+ * The host's `world-agents.v1` answer in the form the world draws. null when the host gave none (the
845
+ * feature is off, or the host has no such projection): the world is then drawn exactly as before. An
846
+ * answer that failed or does not keep the contract is `unavailable` — said out loud, never zero.
847
+ */
848
+ export function normalizeWorldAgents(answer) {
849
+ if (answer === null || answer === undefined) return null;
850
+ if (typeof answer !== 'object' || answer.status === 'failed') {
851
+ return { read: 'unavailable', reason: agentText(answer?.reason) ?? 'request_failed', agents: [], checked_at: null, viewer_scope: null };
852
+ }
853
+ if (answer.contract_version !== WORLD_AGENTS_CONTRACT_VERSION || !Array.isArray(answer.agents)) {
854
+ return { read: 'unavailable', reason: 'contract_mismatch', agents: [], checked_at: null, viewer_scope: null };
855
+ }
856
+ if (answer.is_canonical_judgment !== false) {
857
+ // The projection must say it is not the judgment record; one that does not is not drawn as agents.
858
+ return { read: 'unavailable', reason: 'canonical_flag_missing', agents: [], checked_at: null, viewer_scope: null };
859
+ }
860
+ const checkedAt = agentText(answer.checked_at);
861
+ const agents = [];
862
+ const seen = new Set();
863
+ for (const entry of answer.agents) {
864
+ const id = agentText(entry?.agent_id);
865
+ const name = agentText(entry?.display_name);
866
+ if (!id || !name || seen.has(id)) continue;
867
+ seen.add(id);
868
+ const { look, caution } = worldAgentLook(entry);
869
+ const drilldown = entry.drilldown && typeof entry.drilldown === 'object' ? entry.drilldown : {};
870
+ const href = drilldown.available === true && exitHrefKind(drilldown.href) ? drilldown.href : null;
871
+ agents.push({
872
+ id,
873
+ slug: agentText(entry.slug),
874
+ name,
875
+ role: agentText(entry.role_summary),
876
+ zone: entry.zone === 'business' ? 'business' : 'hq',
877
+ home: agentText(entry.home_project_code),
878
+ current: agentText(entry.current_project_code),
879
+ state: AGENT_STATE_KEYS.includes(entry.state) ? entry.state : 'unconfirmed',
880
+ freshness: AGENT_FRESHNESS_KEYS.includes(entry.freshness) ? entry.freshness : 'unconfirmed',
881
+ look,
882
+ caution,
883
+ observed_at: agentText(entry.observed_at),
884
+ age_minutes: agentAgeMinutes(entry, checkedAt),
885
+ summary: agentText(entry.summary_line),
886
+ blocker: agentText(entry.blocker_code),
887
+ needs_you_count: agentCount(entry.metrics?.needs_you_count),
888
+ drilldown: { href, reason: href ? null : agentText(drilldown.unavailable_reason) ?? '降り口がありません' },
889
+ });
890
+ }
891
+ // Strongest first, so lists and the HQ rows begin with what needs a person.
892
+ agents.sort((a, b) => WORLD_AGENT_LOOKS[b.look].rank - WORLD_AGENT_LOOKS[a.look].rank);
893
+ const read = answer.read_state === 'unavailable' ? 'unavailable' : answer.read_state === 'partial' ? 'partial' : 'confirmed';
894
+ return { read, reason: read === 'unavailable' ? agentText(answer.reason) ?? 'read_state_unavailable' : null, agents, checked_at: checkedAt, viewer_scope: answer.viewer_scope === 'member' ? 'member' : 'owner' };
895
+ }
896
+
897
+ /** Counts of the looks, for the pulse line and the one actionable banner row. */
898
+ export function worldAgentCounts(projection) {
899
+ const counts = { total: 0, working: 0, needs_you: 0, blocked: 0, stale: 0, idle: 0, unconfirmed: 0 };
900
+ for (const agent of projection?.agents ?? []) {
901
+ counts.total += 1;
902
+ counts[agent.look] += 1;
903
+ }
904
+ return counts;
905
+ }
906
+
907
+ /**
908
+ * The line under 世界のいま, kept apart from the businesses' own count (never added to it):
909
+ * `稼働中のAI(Orca投影): M / N`, with the exceptions only when there are some.
910
+ */
911
+ export function worldAgentPulseLine(projection) {
912
+ if (!projection) return null;
913
+ if (projection.read === 'unavailable') {
914
+ return { text: '稼働中のAI(Orca投影): 稼働未確認/0件とは確認できません', tone: 'unconfirmed', source: WORLD_AGENT_SOURCE_TEXT };
915
+ }
916
+ const counts = worldAgentCounts(projection);
917
+ const extra = [
918
+ counts.needs_you ? `要確認 ${counts.needs_you}` : null,
919
+ counts.blocked ? `停止 ${counts.blocked}` : null,
920
+ counts.unconfirmed ? `未確認 ${counts.unconfirmed}` : null,
921
+ ].filter(Boolean);
922
+ return {
923
+ text: `稼働中のAI(Orca投影): ${counts.working} / ${counts.total}${extra.length ? `(${extra.join('・')})` : ''}${projection.read === 'partial' ? '・一部だけ読めた' : ''}`,
924
+ tone: counts.needs_you || counts.blocked ? 'attention' : 'info',
925
+ source: WORLD_AGENT_SOURCE_TEXT,
926
+ };
927
+ }
928
+
929
+ /** The state words of one agent: `要決裁(Orca投影・3分前確認)`, with the freshness caution when it applies. */
930
+ export function worldAgentStateText(agent) {
931
+ const look = WORLD_AGENT_LOOKS[agent.look];
932
+ const age = agent.age_minutes === null ? '確認時刻不明' : `${agent.age_minutes}分前確認`;
933
+ if (agent.look === 'unconfirmed') return '稼働未確認/0件とは確認できません';
934
+ if (agent.look === 'stale') return `${agent.state === 'working' ? '稼働灯消灯' : '待機中'}(最終確認 ${agent.age_minutes === null ? '時刻不明' : `${agent.age_minutes}分前`}・最新未確認)`;
935
+ if (agent.caution) return `${look.label}(鮮度注意:${agent.age_minutes === null ? '確認時刻不明' : `${agent.age_minutes}分前時点`}・最新未確認)`;
936
+ return `${look.label}(Orca投影・${age})`;
937
+ }
938
+
939
+ /**
940
+ * Where each agent stands on the world map. An agent of a business stands at the entrance of its city
941
+ * (the side facing the plaza, never in the plaza); one whose business is not on the map, and every
942
+ * cross-business agent, stands in the common headquarters, a zone outside the ring of cities, in the
943
+ * widest gap between them, so the plaza of judgments stays its own place (P9).
944
+ * `layout` is `layoutWorld`'s answer; returns the agents' points, the HQ zone and the extent it needs.
945
+ */
946
+ /**
947
+ * The code of the city (business) an agent's home project stands in: the business itself, or the business a
948
+ * sub-project (engagement, e.g. `eng-1` under `zeims`) belongs to. null when neither is on the map. The map
949
+ * placement and the card / lists use this one rule, so they never disagree about where an agent is.
950
+ */
951
+ export function worldAgentCityCode(code, businesses = []) {
952
+ if (!code) return null;
953
+ if (businesses.some((business) => business?.code === code)) return code;
954
+ const parent = businesses.find((business) => (business?.engagements ?? []).some((engagement) => engagement?.code === code));
955
+ return parent?.code ?? null;
956
+ }
957
+
958
+ export function placeWorldAgents(projection, layout, { plazaRadius = 7, cityRing = 30 } = {}) {
959
+ const agents = projection?.agents ?? [];
960
+ const cities = layout?.cities ?? [];
961
+ const cityByCode = new Map(cities.filter((city) => city.business?.code).map((city) => [city.business.code, city]));
962
+ const businesses = cities.map((city) => city.business).filter(Boolean);
963
+ const placed = [];
964
+ const hqAgents = [];
965
+ const atCity = new Map();
966
+ for (const agent of agents) {
967
+ const city = agent.zone === 'business' && agent.home ? cityByCode.get(worldAgentCityCode(agent.home, businesses)) ?? null : null;
968
+ if (city) {
969
+ if (!atCity.has(city)) atCity.set(city, []);
970
+ atCity.get(city).push(agent);
971
+ } else {
972
+ hqAgents.push({ agent, fallback: agent.zone === 'business' ? 'business_not_on_map' : null });
973
+ }
974
+ }
975
+ for (const [city, list] of atCity) {
976
+ const distance = Math.hypot(city.x, city.z) || 1;
977
+ const toward = { x: -city.x / distance, z: -city.z / distance };
978
+ const side = { x: -toward.z, z: toward.x };
979
+ const gate = city.size / 2 + 1.6;
980
+ list.forEach((agent, index) => {
981
+ const offset = (index - (list.length - 1) / 2) * 1.5;
982
+ placed.push({ agent, zone: 'business', city: city.business.code, x: city.x + toward.x * gate + side.x * offset, z: city.z + toward.z * gate + side.z * offset, fallback: null });
983
+ });
984
+ }
985
+ // The widest gap between the cities' directions, so the HQ stands clear of every city and of the plaza.
986
+ const angles = cities.map((city) => Math.atan2(city.z, city.x)).sort((a, b) => a - b);
987
+ let angle = Math.PI / 4;
988
+ if (angles.length) {
989
+ let widest = -1;
990
+ angles.forEach((value, index) => {
991
+ const next = index === angles.length - 1 ? angles[0] + Math.PI * 2 : angles[index + 1];
992
+ if (next - value > widest) {
993
+ widest = next - value;
994
+ angle = value + (next - value) / 2;
995
+ }
996
+ });
997
+ }
998
+ const columns = 4;
999
+ const spacing = 2.4;
1000
+ const rows = Math.max(1, Math.ceil(hqAgents.length / columns));
1001
+ const hqWidth = columns * spacing + 2;
1002
+ const hqDepth = rows * spacing + 2;
1003
+ const reach = Math.max(hqWidth, hqDepth) / 2;
1004
+ const cityReach = cities.reduce((max, city) => Math.max(max, Math.hypot(city.x, city.z) + city.size * 0.75), 0);
1005
+ const radius = Math.max(cityRing, plazaRadius + 14, cities.length ? cityReach + reach + 4 : 0);
1006
+ const hq = { x: Math.cos(angle) * radius, z: Math.sin(angle) * radius, width: hqWidth, depth: hqDepth, angle, count: hqAgents.length };
1007
+ hqAgents.forEach(({ agent, fallback }, index) => {
1008
+ const column = index % columns;
1009
+ const row = Math.floor(index / columns);
1010
+ placed.push({ agent, zone: 'hq', city: null, x: hq.x + (column - (columns - 1) / 2) * spacing, z: hq.z + (row - (rows - 1) / 2) * spacing, fallback });
1011
+ });
1012
+ return { placed, hq: hqAgents.length ? hq : null, extent: Math.max(layout?.extent ?? 0, hqAgents.length ? radius + reach + 2 : 0) };
1013
+ }
1014
+
1015
+ /**
1016
+ * What opening one agent shows (at most five items, no approve or rewrite button): who it is and
1017
+ * where it belongs, its projected state and when it was seen, one non-confidential line, one way down
1018
+ * (or why there is none), and the source line.
1019
+ */
1020
+ export function worldAgentCardBlocks(doc, agent, { businessName = null } = {}) {
1021
+ const belongs = agent.zone === 'business' && businessName ? `担当事業:${businessName}` : agent.zone === 'business' ? `担当事業:${agent.home ?? '未記録'}(地図に無いため共通本部に表示)` : '共通本部';
1022
+ const way = agent.drilldown.href
1023
+ ? el(doc, 'a', { className: 'bb-world-agent-drilldown', text: 'Orcaで開く', attrs: { href: agent.drilldown.href } })
1024
+ : el(doc, 'span', { className: 'bb-world-agent-drilldown is-unavailable', text: `開けません:${agent.drilldown.reason}`, attrs: { 'aria-disabled': 'true' } });
1025
+ return [
1026
+ workspaceRailHead(doc, { kicker: 'AI(Orca投影)', title: agent.name, sub: belongs, lead: agent.role ?? undefined }),
1027
+ workspaceRailBlock(doc, {
1028
+ title: '状態',
1029
+ className: `bb-world-agent-state is-${agent.look}${agent.caution ? ' is-caution' : ''}`,
1030
+ content: workspaceDefinition(doc, [['投影状態', worldAgentStateText(agent)], ['最終確認', shortTime(agent.observed_at) ?? '未確認']]),
1031
+ }),
1032
+ workspaceRailBlock(doc, { title: '要約', content: { text: agent.summary ?? '要約の記録はありません' } }),
1033
+ workspaceRailBlock(doc, { title: '降り口', content: way }),
1034
+ el(doc, 'p', { className: 'bb-world-agent-source', text: WORLD_AGENT_SOURCE_TEXT }),
1035
+ ];
1036
+ }