@unson/brainbase-mcp 0.51.10 → 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.
@@ -32,7 +32,7 @@ import { createDistrictView, DISTRICT_LEGEND } from './world-district.js';
32
32
  import { createWorldCanvasUI, SKY_MODES, skyModeLabel, skyModeIconSvg } from './world-canvas-ui.js';
33
33
  import { workCanvasNotes } from './world-canvas-notes.js';
34
34
  import { canvasTexture, drawFacade, FACADE_SIZES, FACADE_UNITS, gableRoof, hashUnit, muted, paintVertices, roundedPlate, valueNoise } from './world-scenery.js';
35
- import { WORK_STATES, cityPulseChips, createPulsePanel, readReasonShort, workCityBlocks, workGrowthBlock, workPickBlock, workSign, workSignBlocks, workSigns, workSiteBlocks } from './world-work-rail.js';
35
+ import { WORK_STATES, cityPulseChips, createPulsePanel, readReasonShort, workCityBlocks, workGrowthBlock, workPickBlock, workSign, workSignBlocks, workSigns, workSiteBlocks, normalizeWorldAgents, placeWorldAgents, worldAgentCardBlocks, worldAgentCityCode, worldAgentCounts, worldAgentPulseLine, worldAgentStateText, WORLD_AGENT_LOOKS, WORLD_AGENT_SOURCE_TEXT } from './world-work-rail.js';
36
36
  import { exitHrefKind, exitLegend, exitsRailBlock, normalizeBusinessExits } from './world-exits.js';
37
37
  import {
38
38
  makeWorkspaceElement as el,
@@ -435,8 +435,26 @@ function createScene({ doc, stage, labelsLayer, reducedMotion, onPick, onClear,
435
435
  instanced.receiveShadow = true;
436
436
  scene.add(instanced);
437
437
  }
438
+ plantedTrees.push({ trunks: [trunks, treePlacements.slice()], foliage: [[lower, conifers], [upper, conifers], [crowns, broadleaves]] });
438
439
  treePlacements.length = 0;
439
440
  }
441
+ /** The trees planted so far, kept so a place built later (the agents' headquarters) can clear its ground. */
442
+ const plantedTrees = [];
443
+ /** Hides the planted trees within `radius` of (x, z); scenery only. */
444
+ function clearTrees(x, z, radius) {
445
+ const hidden = new THREE.Matrix4().makeScale(0, 0, 0);
446
+ for (const { trunks, foliage } of plantedTrees) {
447
+ for (const [instanced, placements] of [trunks, ...foliage]) {
448
+ let changed = false;
449
+ placements.forEach(([px, pz], index) => {
450
+ if (index >= instanced.count || Math.hypot(px - x, pz - z) > radius) return;
451
+ instanced.setMatrixAt(index, hidden);
452
+ changed = true;
453
+ });
454
+ if (changed) instanced.instanceMatrix.needsUpdate = true;
455
+ }
456
+ }
457
+ }
440
458
 
441
459
  // --- scenery (no data) -----------------------------------------------------
442
460
  function pavingTexture() {
@@ -888,7 +906,7 @@ function createScene({ doc, stage, labelsLayer, reducedMotion, onPick, onClear,
888
906
  const markers = { cities: new Map(), plaza: new Map() };
889
907
  /** code → { city (layout), group, label } */
890
908
  const cityIndex = new Map();
891
- function buildCities({ cities, sectors, extent }, judgmentsByBusiness = new Map()) {
909
+ function buildCities({ cities, sectors, extent }, judgmentsByBusiness = new Map(), reserve = []) {
892
910
  fitExtent(extent);
893
911
  const landRadius = buildTerrain(extent);
894
912
  const roads = [];
@@ -967,7 +985,8 @@ function createScene({ doc, stage, labelsLayer, reducedMotion, onPick, onClear,
967
985
  tree(x + Math.cos(a) * size * 0.42, z + Math.sin(a) * size * 0.42, 0.8, 0.45);
968
986
  }
969
987
  }
970
- countryside(landRadius, cities, roads);
988
+ // `reserve`: places another layer stands on (the agents' headquarters), kept clear of groves.
989
+ countryside(landRadius, [...cities, ...reserve], roads);
971
990
  plantTrees();
972
991
  placeLamps();
973
992
  for (const { kind, angle } of sectors) {
@@ -975,6 +994,107 @@ function createScene({ doc, stage, labelsLayer, reducedMotion, onPick, onClear,
975
994
  }
976
995
  }
977
996
 
997
+ // --- AI agents (story-world-agents-step1-v1) --------------------------------------------------------
998
+ // Fixed places, no wandering: a figure's own colour is quiet; its state is one sign above it whose
999
+ // strength follows WORLD_AGENT_LOOKS (needs_you > blocked > working > idle). Unconfirmed is a grey
1000
+ // figure on a dashed ring, never an idle one.
1001
+ const agentBreaths = [];
1002
+ const agentBoardTextures = new Map();
1003
+ function agentBoardTexture(look) {
1004
+ if (!agentBoardTextures.has(look)) {
1005
+ const entry = WORLD_AGENT_LOOKS[look];
1006
+ agentBoardTextures.set(look, canvasTexture(doc, 64, 64, (ctx, w, h) => {
1007
+ ctx.fillStyle = entry.color;
1008
+ ctx.fillRect(0, 0, w, h);
1009
+ ctx.fillStyle = '#ffffff';
1010
+ ctx.font = 'bold 46px sans-serif';
1011
+ ctx.textAlign = 'center';
1012
+ ctx.textBaseline = 'middle';
1013
+ ctx.fillText(entry.badge ?? '', w / 2, h / 2 + 2);
1014
+ }));
1015
+ }
1016
+ return agentBoardTextures.get(look);
1017
+ }
1018
+ function agentFigure(agent) {
1019
+ const entry = WORLD_AGENT_LOOKS[agent.look];
1020
+ const faded = agent.look === 'unconfirmed' || agent.look === 'stale';
1021
+ const group = new THREE.Group();
1022
+ const body = standard(faded ? 0xb4b9bb : agent.look === 'idle' ? 0xd5d8d2 : 0xe3e0d6, { roughness: 0.85, transparent: faded, opacity: faded ? 0.7 : 1 });
1023
+ group.add(mesh(new THREE.CapsuleGeometry(0.3, 0.42, 4, 12), body, { y: 0.55 }));
1024
+ group.add(mesh(new THREE.SphereGeometry(0.27, 14, 12), standard(faded ? 0xc9cdce : 0xfbf7ee, { roughness: 0.6, transparent: faded, opacity: faded ? 0.7 : 1 }), { y: 1.2 }));
1025
+ let light = null;
1026
+ if (entry.badge) {
1027
+ // The two strong signs differ in shape too: a square board (?) for needs_you, an octagon (!) for blocked.
1028
+ const face = standard(0xffffff, { map: agentBoardTexture(agent.look), emissive: new THREE.Color(entry.color), emissiveIntensity: entry.light, emissiveMap: agentBoardTexture(agent.look) });
1029
+ const edge = standard(0xf3efe6);
1030
+ const board = entry.shape === 'octagon'
1031
+ ? mesh(new THREE.CylinderGeometry(0.42, 0.42, 0.08, 8), [edge, face, edge], { y: 2.05, shadow: false })
1032
+ : mesh(new THREE.BoxGeometry(0.72, 0.72, 0.08), [edge, edge, edge, edge, face, face], { y: 2.05, shadow: false });
1033
+ if (entry.shape === 'octagon') board.rotation.x = Math.PI / 2;
1034
+ group.add(mesh(new THREE.CylinderGeometry(0.03, 0.03, 0.5, 6), standard(0x4b524e), { y: 1.55, shadow: false }));
1035
+ group.add(board);
1036
+ light = face;
1037
+ } else if (entry.light > 0) {
1038
+ // Working: one small, steady dot (weaker than either strong sign, and never bouncing).
1039
+ light = standard(0xffffff, { emissive: new THREE.Color(entry.color), emissiveIntensity: entry.light, roughness: 0.4 });
1040
+ group.add(mesh(new THREE.SphereGeometry(0.1, 10, 8), light, { y: 1.6, shadow: false }));
1041
+ }
1042
+ if (agent.look === 'unconfirmed' || agent.caution) {
1043
+ // A dashed ring on the ground: unconfirmed (grey), or a strong sign whose freshness is in doubt.
1044
+ const points = [];
1045
+ for (let i = 0; i <= 48; i += 1) points.push(new THREE.Vector3(Math.cos((i / 48) * Math.PI * 2) * 0.75, 0.06, Math.sin((i / 48) * Math.PI * 2) * 0.75));
1046
+ const ring = new THREE.Line(new THREE.BufferGeometry().setFromPoints(points), new THREE.LineDashedMaterial({ color: agent.look === 'unconfirmed' ? 0x7d8589 : 0x6f6a60, dashSize: 0.18, gapSize: 0.12 }));
1047
+ ring.computeLineDistances();
1048
+ group.add(ring);
1049
+ }
1050
+ group.userData.light = light;
1051
+ group.userData.lightLevel = light ? entry.light : 0;
1052
+ return group;
1053
+ }
1054
+ /** Draws the agents at the places `placeWorldAgents` gave, and the common headquarters they share. */
1055
+ function buildAgents({ placed, hq }) {
1056
+ if (hq) {
1057
+ const zone = new THREE.Group();
1058
+ zone.position.set(hq.x, 0, hq.z);
1059
+ zone.rotation.y = -hq.angle + Math.PI / 2;
1060
+ zone.add(mesh(roundedPlate(hq.width + 0.8, hq.depth + 0.8, 0.16, 1.2), standard(0xc9c4b6, { roughness: 1 })));
1061
+ zone.add(mesh(roundedPlate(hq.width, hq.depth, 0.32, 1), standard(0xe6e2d6, { roughness: 0.95 })));
1062
+ scene.add(zone);
1063
+ register(zone, { kind: 'agentHq' });
1064
+ // The exceptions at the headquarters are counted on its name too, so a hidden overlapping name never hides one.
1065
+ const here = placed.filter((place) => place.zone === 'hq').map((place) => place.agent);
1066
+ const exceptions = [['needs_you', '要決裁'], ['blocked', '停止']].map(([look, word]) => [word, here.filter((agent) => agent.look === look).length]).filter(([, count]) => count > 0);
1067
+ const label = addLabel(`共通本部(AI・Orca投影)${exceptions.map(([word, count]) => `・${word} ${count}`).join('')}`, new THREE.Vector3(hq.x, 0.6, hq.z + hq.depth / 2 + 1), `is-agent-hq${exceptions.length ? ' has-exception' : ''}`, { priority: exceptions.length ? LABEL_PRIORITY.plaza : LABEL_PRIORITY.sector, owner: zone });
1068
+ label.node.classList.add('is-enterable');
1069
+ label.node.title = '共通本部のAIを見る';
1070
+ label.node.addEventListener('click', () => onPick({ kind: 'agentHq' }, new THREE.Vector3(hq.x, 0, hq.z)));
1071
+ }
1072
+ for (const place of placed) {
1073
+ const { agent } = place;
1074
+ const figure = agentFigure(agent);
1075
+ figure.position.set(place.x, place.zone === 'hq' ? 0.32 : 0, place.z);
1076
+ scene.add(figure);
1077
+ register(figure, { ...figure.userData, kind: 'agent', agent });
1078
+ if (figure.userData.light && WORLD_AGENT_LOOKS[agent.look].breathe) agentBreaths.push(figure.userData);
1079
+ const strong = agent.look === 'needs_you' || agent.look === 'blocked';
1080
+ // Only the exceptions are named from afar; the others are named once the viewer comes close.
1081
+ const label = addLabel(strong ? `${agent.name}・${WORLD_AGENT_LOOKS[agent.look].label}${agent.caution ? '(鮮度注意)' : ''}` : agent.name, new THREE.Vector3(place.x, 2.7, place.z), `is-agent is-${agent.look}${agent.caution ? ' is-caution' : ''}`, { minZoom: strong ? 0 : 2.4, priority: strong ? LABEL_PRIORITY.city : LABEL_PRIORITY.engagement, owner: figure });
1082
+ label.node.classList.add('is-enterable');
1083
+ label.node.title = `${agent.name}の状態を見る`;
1084
+ label.node.addEventListener('click', () => onPick({ kind: 'agent', agent }, figure.position.clone()));
1085
+ }
1086
+ }
1087
+
1088
+ /**
1089
+ * The agents arriving after the world was drawn (their read is optional and never holds the world back):
1090
+ * the headquarters' ground is cleared of trees and the view is fitted to reach it, then they are drawn.
1091
+ */
1092
+ function addAgents(places) {
1093
+ if (places.hq) clearTrees(places.hq.x, places.hq.z, Math.hypot(places.hq.width, places.hq.depth) / 2 + 1);
1094
+ if (places.extent > worldExtent) fitExtent(places.extent);
1095
+ buildAgents(places);
1096
+ }
1097
+
978
1098
  // --- selection & hover -------------------------------------------------
979
1099
  const selectionRing = mesh(new THREE.RingGeometry(1, 1.035, 96), new THREE.MeshBasicMaterial({ color: 0x087d62, transparent: true, opacity: 0.9, side: THREE.DoubleSide }), { y: 0.08, shadow: false });
980
1100
  selectionRing.rotation.x = -Math.PI / 2;
@@ -1405,6 +1525,8 @@ function createScene({ doc, stage, labelsLayer, reducedMotion, onPick, onClear,
1405
1525
  ring.scale.setScalar(1 + 0.08 * Math.sin(time / 900));
1406
1526
  }
1407
1527
  if (selectionRing.visible) selectionRing.material.opacity = 0.6 + 0.35 * wave;
1528
+ // needs_you breathes once every 3.6 s (never a blink); under reduced motion it stays still.
1529
+ for (const agent of agentBreaths) agent.light.emissiveIntensity = agent.lightLevel * (0.82 + 0.18 * (1 + Math.sin((time / 3600) * Math.PI * 2)) / 2);
1408
1530
  }
1409
1531
  if (!flight) controls.update();
1410
1532
  renderer.render(scene, camera);
@@ -1415,6 +1537,8 @@ function createScene({ doc, stage, labelsLayer, reducedMotion, onPick, onClear,
1415
1537
  return {
1416
1538
  buildPlaza,
1417
1539
  buildCities,
1540
+ buildAgents,
1541
+ addAgents,
1418
1542
  markChanges,
1419
1543
  /** The sky: 'auto' follows the hour; 'day', 'dusk' or 'night' fix it. Returns the phase shown. */
1420
1544
  setSky(mode) {
@@ -1551,7 +1675,7 @@ const NIGHT_STATES = {
1551
1675
  /** The memory loop as world notes (story-world-memory-status-v1). Unknown is never shown as zero. */
1552
1676
  function memoryLines(answer) {
1553
1677
  if (answer.status === 'not_connected') {
1554
- return [{ text: '記憶の整理:未接続。この画面は夜の整理の結果と記憶の候補を受け取れません。候補の件数は0件とは確認できません。', tone: 'info', summary: '記憶の整理:未接続' }];
1678
+ return [{ text: '記憶の整理:未接続。この画面は夜の整理の結果と記憶の候補を受け取れません。候補の件数は0件とは確認できません。', tone: 'info', summary: '記憶の整理:未接続', tier: 'constraint' }];
1555
1679
  }
1556
1680
  if (answer.status !== 'available' && answer.status !== 'partial') {
1557
1681
  return [{ text: `記憶の整理:読めない(${answer.reason ?? '理由不明'})。候補の件数は0件とは確認できません。`, tone: 'warning', summary: '記憶の整理:読めない' }];
@@ -1638,13 +1762,69 @@ function waitingLines(proofs, judgmentHref) {
1638
1762
  return lines;
1639
1763
  }
1640
1764
 
1765
+ /**
1766
+ * @param {() => (object | null | Promise<object | null>)} [options.worldAgents] The AI agents a host projects onto
1767
+ * the world (story-world-agents-step1-v1): a `world-agents.v1` answer (see `WorldAgentsResponse` in
1768
+ * world-extension). Without it, or when it answers null (the host's feature flag is off or it has no such
1769
+ * projection, e.g. a 404), the world is drawn exactly as before. A failed read is said as 稼働未確認, never 0.
1770
+ */
1771
+ async function readWorldAgents(worldAgents, timeoutMs = WORLD_AGENTS_READ_TIMEOUT_MS) {
1772
+ if (typeof worldAgents !== 'function') return null;
1773
+ let timer = null;
1774
+ try {
1775
+ // A read that never answers is said as unconfirmed after a while, never left as nothing (P9).
1776
+ const timeout = new Promise((_, reject) => { timer = setTimeout(() => reject(new Error('timeout')), timeoutMs); });
1777
+ return normalizeWorldAgents(await Promise.race([Promise.resolve().then(() => worldAgents()), timeout]));
1778
+ } catch (error) {
1779
+ return normalizeWorldAgents({ status: 'failed', reason: error instanceof Error ? error.message : 'request_failed' });
1780
+ } finally {
1781
+ clearTimeout(timer);
1782
+ }
1783
+ }
1784
+
1785
+ /** How long the optional agents' read may take before it is said as unconfirmed (the world never waits for it). */
1786
+ export const WORLD_AGENTS_READ_TIMEOUT_MS = 15000;
1787
+
1788
+ /**
1789
+ * The path of the world's businesses. `?include_test=1` on the page (an owner checking the display filter)
1790
+ * is forwarded to the API, so the filtered projects are drawn too; without it the path is unchanged.
1791
+ */
1792
+ export function worldBusinessesPath(search = globalThis.location?.search ?? '') {
1793
+ let value = null;
1794
+ try {
1795
+ value = new URLSearchParams(search ?? '').get('include_test');
1796
+ } catch {
1797
+ value = null;
1798
+ }
1799
+ const on = value !== null && !['', '0', 'false', 'no', 'off'].includes(value.trim().toLowerCase());
1800
+ return on ? '/api/extensions/world/businesses?include_test=1' : '/api/extensions/world/businesses';
1801
+ }
1802
+
1803
+ /**
1804
+ * A `worldAgents` for a host that serves the projection at `path` (an organization web's
1805
+ * `GET /api/extensions/world/agents`): 404 means the host has none (null: the world stays as before);
1806
+ * any other failure is thrown, so the world says the agents are unconfirmed.
1807
+ */
1808
+ export function fetchWorldAgents(fetcher, path = '/api/extensions/world/agents') {
1809
+ return async () => {
1810
+ const response = await fetcher(path);
1811
+ if (response.status === 404) return null;
1812
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
1813
+ return response.json();
1814
+ };
1815
+ }
1816
+
1641
1817
  /** 判断の履歴 in the local web (it was 今日, `#today`, until 2026-10-11; the shell still opens old links). */
1642
1818
  function defaultJudgmentHref(decisionAttemptId) {
1643
1819
  return decisionAttemptId ? `#value-proofs?decision=${encodeURIComponent(decisionAttemptId)}` : '#value-proofs';
1644
1820
  }
1645
1821
 
1646
- export function createWorldView({ root, rail, page, presentation = 'standard', document: explicitDocument, fetcher, projectHref = (project) => `#projects?project=${encodeURIComponent(project.id)}`, taskHref = null, judgmentHref = defaultJudgmentHref, selection = addressSelection(), businessExits = null, memoryStatus = null, waitingQueues = null }) {
1822
+ export function createWorldView({ root, rail, page, presentation = 'standard', document: explicitDocument, fetcher, projectHref = (project) => `#projects?project=${encodeURIComponent(project.id)}`, taskHref = null, judgmentHref = defaultJudgmentHref, selection = addressSelection(), businessExits = null, memoryStatus = null, waitingQueues = null, worldAgents = null }) {
1647
1823
  const exitsEnabled = typeof businessExits === 'function';
1824
+ /** The agents' projection once read: null while the host gives none (then nothing about agents is drawn). */
1825
+ let agentsProjection = null;
1826
+ /** The cities' layout as first drawn (without the agents), so agents arriving later stand in the same world. */
1827
+ let worldLayout = null;
1648
1828
  const doc = explicitDocument ?? globalThis.document;
1649
1829
  const reducedMotion = Boolean(globalThis.matchMedia?.('(prefers-reduced-motion: reduce)').matches);
1650
1830
  const canvasMode = presentation === 'canvas';
@@ -1748,6 +1928,8 @@ export function createWorldView({ root, rail, page, presentation = 'standard', d
1748
1928
  wrap.append(stage);
1749
1929
  canvasUI = createWorldCanvasUI({
1750
1930
  doc, stage, reducedMotion,
1931
+ // Tier A: at most three actionable rows stand at the top; the standing limits gather behind one chip.
1932
+ questLimit: 3,
1751
1933
  context: {
1752
1934
  purpose: '事業と案件、関連する仕事を地図で確認します。',
1753
1935
  knownCityAction: '都市を選ぶと、その事業の区画に入ります。',
@@ -1838,7 +2020,7 @@ export function createWorldView({ root, rail, page, presentation = 'standard', d
1838
2020
  const business = current.level !== 'world' && current.code ? businessOf(current.code) : null;
1839
2021
  let view;
1840
2022
  if (!business) {
1841
- view = { level: 'world', world: worldPulse(knownBusinesses, workSummaries), connected: workConnected };
2023
+ view = { level: 'world', world: worldPulse(knownBusinesses, workSummaries), connected: workConnected, agents: worldAgentPulseLine(agentsProjection) };
1842
2024
  } else {
1843
2025
  const work = workCache.get(business.code);
1844
2026
  if (workConnected === false || work?.status === 'not_connected') view = { level: 'city', state: NOT_CONNECTED_PULSE };
@@ -2603,17 +2785,17 @@ export function createWorldView({ root, rail, page, presentation = 'standard', d
2603
2785
  const result = await readJson(fetcher, '/api/extensions/world/work-summary');
2604
2786
  if (disposed) return;
2605
2787
  if (!result.ok) {
2606
- note('仕事', `仕事の要約を読めません(${result.error})。都市を選ぶと、その事業の仕事を読みにいきます。0件とは確認できません。`, 'warning', '仕事の要約:読込失敗');
2788
+ note('仕事', `仕事の要約を読めません(${result.error})。都市を選ぶと、その事業の仕事を読みにいきます。0件とは確認できません。`, 'warning', '仕事の要約:読込失敗', null, { incident: true });
2607
2789
  return;
2608
2790
  }
2609
2791
  if (result.data?.status === 'not_connected') {
2610
2792
  workConnected = false;
2611
2793
  refreshPulse();
2612
- note('仕事', 'この画面はタスクの正本に接続していないため、都市の中の仕事は描いていません(0件とは確認できません)。', 'warning', '仕事:未接続(0件とは確認できません)');
2794
+ note('仕事', 'この画面はタスクの正本に接続していないため、都市の中の仕事は描いていません(0件とは確認できません)。', 'warning', '仕事:未接続(0件とは確認できません)', null, { tier: 'constraint' });
2613
2795
  return;
2614
2796
  }
2615
2797
  if (result.data?.status !== 'ok') {
2616
- note('仕事', `仕事の要約を読めません(${result.data?.reason ?? result.data?.status ?? '理由不明'})。0件とは確認できません。`, 'warning', '仕事の要約:読めない');
2798
+ note('仕事', `仕事の要約を読めません(${result.data?.reason ?? result.data?.status ?? '理由不明'})。0件とは確認できません。`, 'warning', '仕事の要約:読めない', null, { incident: true });
2617
2799
  return;
2618
2800
  }
2619
2801
  workConnected = true;
@@ -2653,7 +2835,7 @@ export function createWorldView({ root, rail, page, presentation = 'standard', d
2653
2835
  if (unreadable) note('仕事の読込', `仕事を読めなかった事業${unreadable}件。0件とは確認できません。`, 'warning', `仕事が読めない事業 ${unreadable}件`);
2654
2836
  if (partial) {
2655
2837
  const reasons = [...new Set(readable.filter((entry) => entry.state === 'partial').map((entry) => readReasonShort(entry.reason) ?? '理由の記録なし'))].join('・');
2656
- note('仕事の範囲', `一部だけ読めた事業${partial}件(${reasons})。件数は読めた範囲です。区画の入口で、事業ごとの理由と次にすることを見られます。`, 'warning', `仕事が一部だけ読めた事業 ${partial}件(${reasons})`, null, { action: { label: '理由を見る', onClick: showEntrances } });
2838
+ note('仕事の範囲', `一部だけ読めた事業${partial}件(${reasons})。件数は読めた範囲です。区画の入口で、事業ごとの理由と次にすることを見られます。`, 'warning', `仕事が一部だけ読めた事業 ${partial}件(${reasons})`, null, { action: { label: '理由を見る', onClick: showEntrances }, tier: 'constraint' });
2657
2839
  }
2658
2840
  if (needs) note('仕事の記録', `読めた未完了の仕事${needs}件(${cities}事業)に、記録から把握できていないことがあります。仕事の失敗や停止を意味しません。`, 'attention', `記録の要確認 ${needs}件・${cities}事業`, null, { action: { label: '区画を選ぶ', onClick: showEntrances } });
2659
2841
  }
@@ -2668,6 +2850,14 @@ export function createWorldView({ root, rail, page, presentation = 'standard', d
2668
2850
  }
2669
2851
 
2670
2852
  function onPick(data, position) {
2853
+ if (data.kind === 'agent') {
2854
+ showAgent(data.agent);
2855
+ return;
2856
+ }
2857
+ if (data.kind === 'agentHq') {
2858
+ showAgentsRail('hq');
2859
+ return;
2860
+ }
2671
2861
  if (data.kind === 'site') {
2672
2862
  openSite(data.business, data.site);
2673
2863
  return;
@@ -2773,10 +2963,73 @@ export function createWorldView({ root, rail, page, presentation = 'standard', d
2773
2963
  }
2774
2964
  }
2775
2965
 
2966
+ // --- AI agents (story-world-agents-step1-v1): drawn only when the host gives the projection ------------
2967
+ /** One actionable row for the exceptions, or one for a failed read; the normal state stays in help only. */
2968
+ function agentNotes(note) {
2969
+ const pulse = worldAgentPulseLine(agentsProjection);
2970
+ if (agentsProjection.read === 'unavailable') {
2971
+ note('AI', `稼働中のAIを読めません(${agentsProjection.reason ?? '理由不明'})。稼働未確認です。0件とは確認できません。${WORLD_AGENT_SOURCE_TEXT}。`, 'warning', 'AIの稼働:未確認(0件とは確認できません)', null, { incident: true });
2972
+ return;
2973
+ }
2974
+ const counts = worldAgentCounts(agentsProjection);
2975
+ const exceptions = [counts.needs_you ? `確認待ち ${counts.needs_you}体` : null, counts.blocked ? `停止中 ${counts.blocked}体` : null].filter(Boolean);
2976
+ const text = `${pulse.text}。${WORLD_AGENT_SOURCE_TEXT}。判断の記録(広場)とは別に、各事業の入口と共通本部に立っています。`;
2977
+ if (exceptions.length) note('AI', text, 'attention', `AI(Orca投影):${exceptions.join('・')}`, null, { action: { label: '見る', onClick: () => showAgentsRail('exceptions') } });
2978
+ else note('AI', text);
2979
+ }
2980
+ /** The business (city) an agent's home stands in, a sub-project resolved to its parent city as on the map. */
2981
+ function agentBusiness(agent) {
2982
+ const code = worldAgentCityCode(agent.home, knownBusinesses);
2983
+ return code ? businessOf(code) : null;
2984
+ }
2985
+ /** Opens one agent's minimal card in the rail (at most five items; no approve or rewrite button). */
2986
+ function showAgent(agent) {
2987
+ showRail(worldAgentCardBlocks(doc, agent, { businessName: agentBusiness(agent)?.name ?? null }));
2988
+ canvasUI?.openRail();
2989
+ }
2990
+ /** The agents as a list in the rail: the exceptions, those at the headquarters, or all. */
2991
+ function showAgentsRail(which = 'all') {
2992
+ if (!agentsProjection) return;
2993
+ const agents = agentsProjection.agents.filter((agent) => which === 'exceptions' ? agent.look === 'needs_you' || agent.look === 'blocked' : which === 'hq' ? agent.zone === 'hq' || !agentBusiness(agent) : true);
2994
+ const list = el(doc, 'ul', { className: 'bb-world-agent-list' });
2995
+ for (const agent of agents) {
2996
+ const item = el(doc, 'li');
2997
+ const button = el(doc, 'button', { className: `bb-world-agent-row is-${agent.look}${agent.caution ? ' is-caution' : ''}`, attrs: { type: 'button' } });
2998
+ button.append(el(doc, 'span', { className: 'bb-world-agent-mark', attrs: { 'aria-hidden': 'true' }, text: WORLD_AGENT_LOOKS[agent.look].badge ?? '' }), el(doc, 'span', { className: 'bb-world-agent-name', text: agent.name }), el(doc, 'span', { className: 'bb-world-agent-row-state', text: worldAgentStateText(agent) }));
2999
+ button.addEventListener('click', () => showAgent(agent));
3000
+ item.append(button);
3001
+ list.append(item);
3002
+ }
3003
+ showRail([
3004
+ workspaceRailHead(doc, { kicker: 'AI(Orca投影)', title: which === 'hq' ? '共通本部' : which === 'exceptions' ? '確認待ち・停止中のAI' : 'AI', lead: worldAgentPulseLine(agentsProjection).text }),
3005
+ workspaceRailBlock(doc, { title: '', content: agents.length ? list : { text: 'ありません' } }),
3006
+ el(doc, 'p', { className: 'bb-world-agent-source', text: WORLD_AGENT_SOURCE_TEXT }),
3007
+ ]);
3008
+ canvasUI?.openRail();
3009
+ }
3010
+ /** Without 3D the agents are a list under the businesses, each opening the same card. */
3011
+ function renderAgentList(container) {
3012
+ const section = el(doc, 'div', { className: 'bb-world-fallback bb-world-agent-fallback' });
3013
+ section.append(el(doc, 'h2', { text: 'AI(Orca投影)' }), el(doc, 'p', { text: worldAgentPulseLine(agentsProjection).text }));
3014
+ const list = el(doc, 'ul', { className: 'bb-world-agent-list' });
3015
+ for (const agent of agentsProjection.agents) {
3016
+ const item = el(doc, 'li');
3017
+ const button = el(doc, 'button', { className: `bb-world-agent-row is-${agent.look}${agent.caution ? ' is-caution' : ''}`, attrs: { type: 'button' } });
3018
+ const where = agent.zone === 'business' && agentBusiness(agent) ? agentBusiness(agent).name : '共通本部';
3019
+ button.append(el(doc, 'span', { className: 'bb-world-agent-name', text: `${agent.name}(${where})` }), el(doc, 'span', { className: 'bb-world-agent-row-state', text: worldAgentStateText(agent) }));
3020
+ button.addEventListener('click', () => showAgent(agent));
3021
+ item.append(button);
3022
+ list.append(item);
3023
+ }
3024
+ section.append(list, el(doc, 'p', { className: 'bb-world-agent-source', text: WORLD_AGENT_SOURCE_TEXT }));
3025
+ container.append(section);
3026
+ }
3027
+
2776
3028
  async function load() {
2777
3029
  const memoryRead = readMemoryStatus(memoryStatus);
2778
3030
  const queuesRead = readWaitingQueues(waitingQueues);
2779
- const businessesResult = await readJson(fetcher, '/api/extensions/world/businesses');
3031
+ const agentsRead = readWorldAgents(worldAgents);
3032
+ const businessesResult = await readJson(fetcher, worldBusinessesPath());
2780
3033
  if (disposed) return;
2781
3034
  // A world drawn from an organization's Graph shows only that organization's judgments: the host keeps
2782
3035
  // the others (another company's work, or unknown) back and sends only how many it kept back.
@@ -2798,9 +3051,9 @@ export function createWorldView({ root, rail, page, presentation = 'standard', d
2798
3051
  }
2799
3052
  if (disposed) return;
2800
3053
  notices.replaceChildren();
2801
- const note = (label, textValue, tone = 'info', summary = null, link = null, { action = null, reason = null } = {}) => {
3054
+ const note = (label, textValue, tone = 'info', summary = null, link = null, { action = null, reason = null, tier = null, incident = false } = {}) => {
2802
3055
  if (canvasUI) {
2803
- setCanvasNote(`${label}:${summary ?? 'detail'}`, { label, text: textValue, tone, summary, link, action, reason });
3056
+ setCanvasNote(`${label}:${summary ?? 'detail'}`, { label, text: textValue, tone, summary, link, action, reason, tier, incident });
2804
3057
  return;
2805
3058
  }
2806
3059
  const line = el(doc, 'p', { className: `bb-world-hud-line is-${tone}`, attrs: tone === 'info' ? {} : { role: 'alert' } });
@@ -2814,7 +3067,7 @@ export function createWorldView({ root, rail, page, presentation = 'standard', d
2814
3067
  if (exitsEnabled) renderExitLegend();
2815
3068
  if (!businessesResult.ok || businessPayload?.status !== 'ok') {
2816
3069
  const reason = businessesResult.ok ? `${BUSINESS_STATE_TEXT[businessPayload?.status] ?? '状態不明'}(${businessPayload?.reason ?? '理由不明'})` : `取得に失敗しました(${businessesResult.error})`;
2817
- note('事業', `${reason}。事業の件数は未確認です。0件とは確認できません。`, 'warning', '事業:読めない(0件とは確認できません)');
3070
+ note('事業', `${reason}。事業の件数は未確認です。0件とは確認できません。`, 'warning', '事業:読めない(0件とは確認できません)', null, { incident: true });
2818
3071
  } else {
2819
3072
  const extra = [];
2820
3073
  if (businessPayload.unplaced.length) extra.push(`親の事業がGraphに無い案件${businessPayload.unplaced.length}件は描いていません`);
@@ -2826,7 +3079,9 @@ export function createWorldView({ root, rail, page, presentation = 'standard', d
2826
3079
  extra.push('組織の用語を読めないため、分類の名前は語彙ファイルか値のままです');
2827
3080
  if (canvasMode) note('用語', '組織の用語を読めないため、分類の名前は語彙ファイルか値のままです。', 'warning', '組織の用語:読めない');
2828
3081
  }
2829
- if (canvasMode && businessPayload.unplaced.length) note('案件', '親の事業がGraphに無い案件は描いていません。', 'warning', `親の事業が見つからない案件 ${businessPayload.unplaced.length}件`);
3082
+ if (canvasMode && businessPayload.unplaced.length) note('案件', '親の事業がGraphに無い案件は描いていません。', 'warning', `親の事業が見つからない案件 ${businessPayload.unplaced.length}件`, null, { tier: 'constraint' });
3083
+ // The display filter keeps test and finished projects off the map; how many is said, never dropped silently.
3084
+ if (Number.isInteger(businessPayload.filtered_out_count) && businessPayload.filtered_out_count > 0) extra.push(`テスト用・終了した事業など${businessPayload.filtered_out_count}件は地図に出していません(記録は消していません)`);
2830
3085
  note('事業', `${sourceText}の事業${businesses.length}件・案件${businesses.reduce((sum, business) => sum + business.engagements.length, 0)}件。${extra.join('。')}${extra.length ? '。' : ''}`);
2831
3086
  }
2832
3087
  const home = homeResult.ok ? homeResult.data : null;
@@ -2837,8 +3092,8 @@ export function createWorldView({ root, rail, page, presentation = 'standard', d
2837
3092
  judgmentsUnavailable = JUDGMENT_UNAVAILABLE_TEXT[reason]
2838
3093
  ? { title: '判断の記録:未接続', text: `${JUDGMENT_UNAVAILABLE_TEXT[reason]}。`, short: JUDGMENT_UNAVAILABLE_SHORT[reason] }
2839
3094
  : { title: '判断の記録:読めない', text: `判断の記録を読めません(${reason})。判断の記録の件数は未確認です。0件とは確認できません。`, short: `理由:${reason}` };
2840
- if (JUDGMENT_UNAVAILABLE_TEXT[reason]) note('判断', `${JUDGMENT_UNAVAILABLE_TEXT[reason]}。事業だけを描いています。`, 'warning', '判断の記録:未接続', null, { reason: judgmentsUnavailable.short });
2841
- else note('判断', judgmentsUnavailable.text, 'warning', '判断の記録:読めない', null, { reason: judgmentsUnavailable.short });
3095
+ if (JUDGMENT_UNAVAILABLE_TEXT[reason]) note('判断', `${JUDGMENT_UNAVAILABLE_TEXT[reason]}。事業だけを描いています。`, 'warning', '判断の記録:未接続', null, { reason: judgmentsUnavailable.short, tier: 'constraint' });
3096
+ else note('判断', judgmentsUnavailable.text, 'warning', '判断の記録:読めない', null, { reason: judgmentsUnavailable.short, incident: true });
2842
3097
  } else {
2843
3098
  proofs = proofIndex(home);
2844
3099
  judgmentsConnected = true;
@@ -2864,7 +3119,28 @@ export function createWorldView({ root, rail, page, presentation = 'standard', d
2864
3119
  const rowItems = new Map(rows.map((row) => [row.key, Array.isArray(row.items) ? row.items : []]));
2865
3120
  const memory = await memoryRead;
2866
3121
  if (disposed) return;
2867
- for (const line of memoryLines(memory)) note('記憶', line.text, line.tone, line.summary, line.link);
3122
+ for (const line of memoryLines(memory)) note('記憶', line.text, line.tone, line.summary, line.link, { tier: line.tier ?? null });
3123
+ // The agents' read is optional: the world is drawn now with whatever it answered so far (nothing while it
3124
+ // is still pending), and the agents are added to it when it answers (applyAgents below).
3125
+ const AGENTS_PENDING = Symbol('pending');
3126
+ const agentsEarly = await Promise.race([agentsRead, Promise.resolve(AGENTS_PENDING)]);
3127
+ if (disposed) return;
3128
+ const agentsPending = agentsEarly === AGENTS_PENDING;
3129
+ agentsProjection = agentsPending ? null : agentsEarly;
3130
+ if (agentsProjection) agentNotes(note);
3131
+ /** Draws the agents that arrived after the world: the banner row, the list or the figures, and the pulse line. */
3132
+ const applyAgents = (projection) => {
3133
+ if (disposed || !projection) return;
3134
+ agentsProjection = projection;
3135
+ agentNotes(note);
3136
+ if (scene && worldLayout) scene.addAgents(placeWorldAgents(projection, worldLayout, { plazaRadius: PLAZA_RADIUS, cityRing: CITY_RING }));
3137
+ else if (fallbackStage) renderAgentList(fallbackStage);
3138
+ refreshPulse();
3139
+ };
3140
+ let fallbackStage = null;
3141
+ const lateAgents = () => {
3142
+ if (agentsPending) void agentsRead.then(applyAgents);
3143
+ };
2868
3144
 
2869
3145
  knownBusinesses = businesses;
2870
3146
  canvasUI?.setCities(businesses, current.code);
@@ -2873,8 +3149,10 @@ export function createWorldView({ root, rail, page, presentation = 'standard', d
2873
3149
  if (webgl === 'slow') note('表示', 'この環境ではGPUを使えず、3Dの描画が非常に遅いため、一覧で出しています。', 'warning', '3D表示が遅い環境・一覧表示');
2874
3150
  else note('表示', 'この環境では3Dを表示できないため、一覧で出しています。', 'warning', '3D表示を利用できません・一覧表示');
2875
3151
  const exitSlot = exitsEnabled ? fallbackExitSlot : null;
3152
+ fallbackStage = stage;
2876
3153
  if (canvasMode) {
2877
3154
  renderFallbackList(doc, stage, businesses, rows, exitSlot);
3155
+ if (agentsProjection) renderAgentList(stage);
2878
3156
  pulseReady = true;
2879
3157
  refreshPulse();
2880
3158
  showEmptyRail();
@@ -2883,14 +3161,22 @@ export function createWorldView({ root, rail, page, presentation = 'standard', d
2883
3161
  } else {
2884
3162
  stage.classList.add('is-fallback');
2885
3163
  renderFallbackList(doc, stage, businesses, rows, exitSlot);
3164
+ if (agentsProjection) renderAgentList(stage);
2886
3165
  }
2887
3166
  for (const business of exitsEnabled ? businesses : []) loadExits(business);
3167
+ lateAgents();
2888
3168
  return;
2889
3169
  }
2890
3170
  scene = createScene({ doc, stage, labelsLayer, reducedMotion, onPick, onClear: clearAll, onEscape: goUp, onSign: (business, code) => showSignMeaning(business ?? knownBusinesses.find((entry) => entry.code === code) ?? null) });
2891
3171
  scene.setSky(SKY_MODES[skyIndex].value);
2892
3172
  scene.buildPlaza(rows, rowItems, (row) => (rowItems.get(row.key) ?? []).filter((ref) => isWaiting(proofs.get(ref.decision_attempt_id))).length, Date.now(), { state: judgmentsUnavailable ? judgmentsUnavailable.title.replace('判断の記録:', '') : null });
2893
- scene.buildCities(layoutWorld(businesses), placement.byBusiness);
3173
+ const layout = layoutWorld(businesses);
3174
+ worldLayout = { ...layout };
3175
+ // The agents' places come first, so the land reaches their headquarters (nothing changes without them).
3176
+ const agentPlaces = agentsProjection ? placeWorldAgents(agentsProjection, layout, { plazaRadius: PLAZA_RADIUS, cityRing: CITY_RING }) : null;
3177
+ if (agentPlaces) layout.extent = agentPlaces.extent;
3178
+ scene.buildCities(layout, placement.byBusiness, agentPlaces?.hq ? [{ x: agentPlaces.hq.x, z: agentPlaces.hq.z, size: Math.max(agentPlaces.hq.width, agentPlaces.hq.depth) }] : []);
3179
+ if (agentPlaces) scene.buildAgents(agentPlaces);
2894
3180
  showChangesSinceLastVisit(note, businesses, rows);
2895
3181
  knownBusinesses = businesses;
2896
3182
  pulseReady = true;
@@ -2899,6 +3185,7 @@ export function createWorldView({ root, rail, page, presentation = 'standard', d
2899
3185
  if (!current.code) showEmptyRail();
2900
3186
  restoreSelection();
2901
3187
  void loadWorkSummary(note);
3188
+ lateAgents();
2902
3189
  }
2903
3190
 
2904
3191
  /**