@agenticmail/enterprise 0.5.300 → 0.5.302

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 (46) hide show
  1. package/dist/chunk-QKQWDX6M.js +1519 -0
  2. package/dist/chunk-VLVRDLYO.js +48 -0
  3. package/dist/chunk-VMVOJFCX.js +4338 -0
  4. package/dist/cli-agent-4GZGC6XO.js +1778 -0
  5. package/dist/cli-recover-WS27YEB7.js +487 -0
  6. package/dist/cli-serve-HVULKNQH.js +143 -0
  7. package/dist/cli-verify-CVYMUGKX.js +149 -0
  8. package/dist/cli.js +5 -5
  9. package/dist/dashboard/components/org-switcher.js +96 -0
  10. package/dist/dashboard/pages/agents.js +8 -1
  11. package/dist/dashboard/pages/approvals.js +5 -1
  12. package/dist/dashboard/pages/dashboard.js +6 -2
  13. package/dist/dashboard/pages/guardrails.js +20 -16
  14. package/dist/dashboard/pages/journal.js +6 -2
  15. package/dist/dashboard/pages/knowledge-contributions.js +18 -10
  16. package/dist/dashboard/pages/knowledge.js +32 -9
  17. package/dist/dashboard/pages/messages.js +8 -4
  18. package/dist/dashboard/pages/org-chart.js +5 -1
  19. package/dist/dashboard/pages/organizations.js +166 -13
  20. package/dist/dashboard/pages/skills.js +15 -11
  21. package/dist/dashboard/pages/task-pipeline.js +6 -2
  22. package/dist/dashboard/pages/workforce.js +5 -1
  23. package/dist/factory-XEBV2VGZ.js +9 -0
  24. package/dist/index.js +3 -3
  25. package/dist/postgres-NZBDKOQR.js +816 -0
  26. package/dist/server-3HZEV5X2.js +15 -0
  27. package/dist/setup-JUB67BUU.js +20 -0
  28. package/dist/sqlite-INPN4DQN.js +545 -0
  29. package/package.json +1 -1
  30. package/src/admin/routes.ts +94 -5
  31. package/src/dashboard/components/org-switcher.js +96 -0
  32. package/src/dashboard/pages/agents.js +8 -1
  33. package/src/dashboard/pages/approvals.js +5 -1
  34. package/src/dashboard/pages/dashboard.js +6 -2
  35. package/src/dashboard/pages/guardrails.js +20 -16
  36. package/src/dashboard/pages/journal.js +6 -2
  37. package/src/dashboard/pages/knowledge-contributions.js +18 -10
  38. package/src/dashboard/pages/knowledge.js +32 -9
  39. package/src/dashboard/pages/messages.js +8 -4
  40. package/src/dashboard/pages/org-chart.js +5 -1
  41. package/src/dashboard/pages/organizations.js +166 -13
  42. package/src/dashboard/pages/skills.js +15 -11
  43. package/src/dashboard/pages/task-pipeline.js +6 -2
  44. package/src/dashboard/pages/workforce.js +5 -1
  45. package/src/db/postgres.ts +17 -0
  46. package/src/db/sqlite.ts +8 -0
@@ -0,0 +1,149 @@
1
+ import {
2
+ DomainLock
3
+ } from "./chunk-UPU23ZRG.js";
4
+ import "./chunk-KFQGP6VL.js";
5
+
6
+ // src/domain-lock/cli-verify.ts
7
+ function getFlag(args, name) {
8
+ const idx = args.indexOf(name);
9
+ if (idx !== -1 && args[idx + 1]) return args[idx + 1];
10
+ return void 0;
11
+ }
12
+ function hasFlag(args, name) {
13
+ return args.includes(name);
14
+ }
15
+ function detectDbType(url) {
16
+ const u = url.toLowerCase().trim();
17
+ if (u.startsWith("postgres") || u.startsWith("pg:")) return "postgres";
18
+ if (u.startsWith("mysql")) return "mysql";
19
+ if (u.startsWith("mongodb")) return "mongodb";
20
+ if (u.startsWith("libsql") || u.includes(".turso.io")) return "turso";
21
+ if (u.endsWith(".db") || u.endsWith(".sqlite") || u.endsWith(".sqlite3") || u.startsWith("file:")) return "sqlite";
22
+ return "postgres";
23
+ }
24
+ async function runVerifyDomain(args) {
25
+ const { default: chalk } = await import("chalk");
26
+ const { default: ora } = await import("ora");
27
+ console.log("");
28
+ console.log(chalk.bold(" AgenticMail Enterprise \u2014 Domain Verification"));
29
+ console.log("");
30
+ let domain = getFlag(args, "--domain");
31
+ let dnsChallenge;
32
+ let db = null;
33
+ let dbConnected = false;
34
+ const envDbUrl = process.env.DATABASE_URL;
35
+ if (envDbUrl) {
36
+ const dbType = detectDbType(envDbUrl);
37
+ const spinner = ora(`Connecting to database (${dbType})...`).start();
38
+ try {
39
+ const { createAdapter } = await import("./factory-XEBV2VGZ.js");
40
+ db = await createAdapter({ type: dbType, connectionString: envDbUrl });
41
+ await db.migrate();
42
+ const settings = await db.getSettings();
43
+ if (!domain && settings?.domain) domain = settings.domain;
44
+ if (settings?.domainDnsChallenge) dnsChallenge = settings.domainDnsChallenge;
45
+ dbConnected = true;
46
+ spinner.succeed(`Connected to ${dbType} database` + (domain ? ` (domain: ${domain})` : ""));
47
+ } catch (err) {
48
+ spinner.warn(`Could not connect via DATABASE_URL: ${err.message}`);
49
+ db = null;
50
+ }
51
+ }
52
+ if (!dbConnected) {
53
+ const dbPath = getFlag(args, "--db");
54
+ const dbType = getFlag(args, "--db-type") || "sqlite";
55
+ if (dbPath) {
56
+ const spinner = ora(`Connecting to ${dbType} database...`).start();
57
+ try {
58
+ const { createAdapter } = await import("./factory-XEBV2VGZ.js");
59
+ db = await createAdapter({ type: dbType, connectionString: dbPath });
60
+ await db.migrate();
61
+ const settings = await db.getSettings();
62
+ if (!domain && settings?.domain) domain = settings.domain;
63
+ if (settings?.domainDnsChallenge) dnsChallenge = settings.domainDnsChallenge;
64
+ dbConnected = true;
65
+ spinner.succeed(`Connected to ${dbType} database`);
66
+ } catch {
67
+ spinner.warn("Could not read local database");
68
+ }
69
+ }
70
+ }
71
+ if (!domain) {
72
+ const { default: inquirer } = await import("inquirer");
73
+ const answer = await inquirer.prompt([{
74
+ type: "input",
75
+ name: "domain",
76
+ message: "Domain to verify:",
77
+ suffix: chalk.dim(" (e.g. agents.yourcompany.com)"),
78
+ validate: (v) => v.includes(".") || "Enter a valid domain",
79
+ filter: (v) => v.trim().toLowerCase()
80
+ }]);
81
+ domain = answer.domain;
82
+ }
83
+ const lock = new DomainLock();
84
+ const maxAttempts = hasFlag(args, "--poll") ? 5 : 1;
85
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
86
+ const spinner = ora(
87
+ maxAttempts > 1 ? `Checking DNS verification (attempt ${attempt}/${maxAttempts})...` : "Checking DNS verification..."
88
+ ).start();
89
+ try {
90
+ const result = await lock.checkVerification(domain);
91
+ if (!result.success) {
92
+ spinner.fail("Verification check failed");
93
+ console.log("");
94
+ console.error(chalk.red(` ${result.error}`));
95
+ console.log("");
96
+ if (db) await db.disconnect();
97
+ process.exit(1);
98
+ }
99
+ if (result.verified) {
100
+ spinner.succeed("Domain verified!");
101
+ if (dbConnected && db) {
102
+ try {
103
+ await db.updateSettings({
104
+ domainStatus: "verified",
105
+ domainVerifiedAt: (/* @__PURE__ */ new Date()).toISOString()
106
+ });
107
+ console.log(chalk.dim(" Database updated with verified status."));
108
+ } catch {
109
+ }
110
+ }
111
+ console.log("");
112
+ console.log(chalk.green.bold(` \u2713 ${domain} is verified and protected.`));
113
+ console.log(chalk.dim(" Your deployment domain is locked. No other instance can claim it."));
114
+ console.log(chalk.dim(" The system now operates 100% offline \u2014 no outbound calls are made."));
115
+ console.log("");
116
+ if (db) await db.disconnect();
117
+ return;
118
+ }
119
+ } catch (err) {
120
+ spinner.warn(`Check failed: ${err.message}`);
121
+ }
122
+ if (attempt < maxAttempts) {
123
+ const waitSpinner = ora(`DNS record not found yet. Retrying in 10 seconds...`).start();
124
+ await new Promise((r) => setTimeout(r, 1e4));
125
+ waitSpinner.stop();
126
+ }
127
+ }
128
+ console.log("");
129
+ console.log(chalk.yellow(" DNS record not detected yet."));
130
+ console.log("");
131
+ console.log(chalk.bold(" Make sure this TXT record exists at your DNS provider:"));
132
+ console.log("");
133
+ console.log(` ${chalk.bold("Host:")} ${chalk.cyan(`_agenticmail-verify.${domain}`)}`);
134
+ console.log(` ${chalk.bold("Type:")} ${chalk.cyan("TXT")}`);
135
+ if (dnsChallenge) {
136
+ console.log(` ${chalk.bold("Value:")} ${chalk.cyan(dnsChallenge)}`);
137
+ } else {
138
+ console.log(` ${chalk.bold("Value:")} ${chalk.dim("(check your dashboard or setup output)")}`);
139
+ }
140
+ console.log("");
141
+ console.log(chalk.dim(" DNS propagation can take up to 48 hours."));
142
+ console.log(chalk.dim(" Run with --poll to retry automatically:"));
143
+ console.log(chalk.dim(` npx @agenticmail/enterprise verify-domain --domain ${domain} --poll`));
144
+ console.log("");
145
+ if (db) await db.disconnect();
146
+ }
147
+ export {
148
+ runVerifyDomain
149
+ };
package/dist/cli.js CHANGED
@@ -14,10 +14,10 @@ switch (command) {
14
14
  import("./cli-submit-skill-LDFJGSKO.js").then((m) => m.runSubmitSkill(args.slice(1))).catch(fatal);
15
15
  break;
16
16
  case "recover":
17
- import("./cli-recover-MFF5AXLN.js").then((m) => m.runRecover(args.slice(1))).catch(fatal);
17
+ import("./cli-recover-WS27YEB7.js").then((m) => m.runRecover(args.slice(1))).catch(fatal);
18
18
  break;
19
19
  case "verify-domain":
20
- import("./cli-verify-BTSN7SQ2.js").then((m) => m.runVerifyDomain(args.slice(1))).catch(fatal);
20
+ import("./cli-verify-CVYMUGKX.js").then((m) => m.runVerifyDomain(args.slice(1))).catch(fatal);
21
21
  break;
22
22
  case "reset-password":
23
23
  import("./cli-reset-password-SO5Y6MW7.js").then((m) => m.runResetPassword(args.slice(1))).catch(fatal);
@@ -57,14 +57,14 @@ Skill Development:
57
57
  break;
58
58
  case "serve":
59
59
  case "start":
60
- import("./cli-serve-BXI7TTNN.js").then((m) => m.runServe(args.slice(1))).catch(fatal);
60
+ import("./cli-serve-HVULKNQH.js").then((m) => m.runServe(args.slice(1))).catch(fatal);
61
61
  break;
62
62
  case "agent":
63
- import("./cli-agent-4DVE3NDA.js").then((m) => m.runAgent(args.slice(1))).catch(fatal);
63
+ import("./cli-agent-4GZGC6XO.js").then((m) => m.runAgent(args.slice(1))).catch(fatal);
64
64
  break;
65
65
  case "setup":
66
66
  default:
67
- import("./setup-KIAPXKEX.js").then((m) => m.runSetupWizard()).catch(fatal);
67
+ import("./setup-JUB67BUU.js").then((m) => m.runSetupWizard()).catch(fatal);
68
68
  break;
69
69
  }
70
70
  function fatal(err) {
@@ -0,0 +1,96 @@
1
+ import { h, useState, useEffect, Fragment, apiCall } from './utils.js';
2
+ import { I } from './icons.js';
3
+
4
+ /**
5
+ * OrgContextSwitcher — Global org context picker for multi-tenant pages.
6
+ *
7
+ * Props:
8
+ * onOrgChange(orgId, org) — called when org selection changes
9
+ * selectedOrgId — currently selected org ID ('' = my org)
10
+ * style — optional container style override
11
+ * showLabel — show "Viewing:" label (default true)
12
+ *
13
+ * The component loads client_organizations from the API and renders a
14
+ * compact dropdown that switches between "My Organization" and client orgs.
15
+ */
16
+ export function OrgContextSwitcher(props) {
17
+ var onOrgChange = props.onOrgChange;
18
+ var selectedOrgId = props.selectedOrgId || '';
19
+ var showLabel = props.showLabel !== false;
20
+ var style = props.style || {};
21
+
22
+ var _orgs = useState([]);
23
+ var orgs = _orgs[0]; var setOrgs = _orgs[1];
24
+ var _loaded = useState(false);
25
+ var loaded = _loaded[0]; var setLoaded = _loaded[1];
26
+
27
+ useEffect(function() {
28
+ apiCall('/organizations').then(function(d) {
29
+ setOrgs(d.organizations || []);
30
+ setLoaded(true);
31
+ }).catch(function() { setLoaded(true); });
32
+ }, []);
33
+
34
+ // Don't render if no client orgs exist
35
+ if (loaded && orgs.length === 0) return null;
36
+ if (!loaded) return null;
37
+
38
+ var selectedOrg = orgs.find(function(o) { return o.id === selectedOrgId; });
39
+
40
+ return h('div', {
41
+ style: Object.assign({
42
+ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 14px',
43
+ background: 'var(--bg-tertiary)', borderRadius: 'var(--radius, 8px)',
44
+ marginBottom: 16, fontSize: 13
45
+ }, style)
46
+ },
47
+ showLabel && h('span', { style: { color: 'var(--text-muted)', fontWeight: 600, whiteSpace: 'nowrap' } }, I.building(), ' Viewing:'),
48
+ h('select', {
49
+ value: selectedOrgId,
50
+ onChange: function(e) {
51
+ var id = e.target.value;
52
+ var org = orgs.find(function(o) { return o.id === id; });
53
+ onOrgChange(id, org || null);
54
+ },
55
+ style: {
56
+ padding: '6px 10px', borderRadius: 6, border: '1px solid var(--border)',
57
+ background: 'var(--bg-card)', color: 'var(--text)', fontSize: 13,
58
+ cursor: 'pointer', fontWeight: 600, flex: 1, maxWidth: 300
59
+ }
60
+ },
61
+ h('option', { value: '' }, 'My Organization'),
62
+ orgs.filter(function(o) { return o.is_active !== false; }).map(function(o) {
63
+ return h('option', { key: o.id, value: o.id }, o.name + (o.billing_rate_per_agent > 0 ? ' (' + (o.currency || 'USD') + ' ' + parseFloat(o.billing_rate_per_agent).toFixed(0) + '/agent)' : ''));
64
+ })
65
+ ),
66
+ selectedOrg && h('span', { style: { fontSize: 11, color: 'var(--text-muted)' } },
67
+ selectedOrg.contact_name ? selectedOrg.contact_name : '',
68
+ selectedOrg.contact_email ? ' \u2022 ' + selectedOrg.contact_email : ''
69
+ )
70
+ );
71
+ }
72
+
73
+ /**
74
+ * useOrgContext — Hook that provides org switching state.
75
+ * Returns [selectedOrgId, selectedOrg, onOrgChange, OrgSwitcher component]
76
+ */
77
+ export function useOrgContext() {
78
+ var _sel = useState('');
79
+ var selectedOrgId = _sel[0]; var setSelectedOrgId = _sel[1];
80
+ var _org = useState(null);
81
+ var selectedOrg = _org[0]; var setSelectedOrg = _org[1];
82
+
83
+ var onOrgChange = function(id, org) {
84
+ setSelectedOrgId(id);
85
+ setSelectedOrg(org);
86
+ };
87
+
88
+ var Switcher = function(extraProps) {
89
+ return h(OrgContextSwitcher, Object.assign({
90
+ selectedOrgId: selectedOrgId,
91
+ onOrgChange: onOrgChange
92
+ }, extraProps || {}));
93
+ };
94
+
95
+ return { selectedOrgId: selectedOrgId, selectedOrg: selectedOrg, onOrgChange: onOrgChange, Switcher: Switcher };
96
+ }
@@ -3,6 +3,7 @@ import { I } from '../components/icons.js';
3
3
  import { E } from '../assets/icons/emoji-icons.js';
4
4
  import { CULTURES, LANGUAGES, PersonaForm } from '../components/persona-fields.js';
5
5
  import { HelpButton } from '../components/help-button.js';
6
+ import { useOrgContext } from '../components/org-switcher.js';
6
7
 
7
8
  // ════════════════════════════════════════════════════════════
8
9
  // DEPLOY MODAL
@@ -1127,6 +1128,7 @@ export function CreateAgentWizard({ onClose, onCreated, toast }) {
1127
1128
  export function AgentsPage({ onSelectAgent }) {
1128
1129
  const app = useApp();
1129
1130
  const toast = app.toast;
1131
+ var orgCtx = useOrgContext();
1130
1132
  const [agents, setAgents] = useState([]);
1131
1133
  const [creating, setCreating] = useState(false);
1132
1134
 
@@ -1138,9 +1140,13 @@ export function AgentsPage({ onSelectAgent }) {
1138
1140
  if (allowedAgents !== '*' && Array.isArray(allowedAgents)) {
1139
1141
  all = all.filter(a => allowedAgents.indexOf(a.id) >= 0);
1140
1142
  }
1143
+ // Filter by selected org context
1144
+ if (orgCtx.selectedOrgId) {
1145
+ all = all.filter(a => a.client_org_id === orgCtx.selectedOrgId);
1146
+ }
1141
1147
  setAgents(all);
1142
1148
  }).catch(() => {});
1143
- useEffect(() => { load(); }, []);
1149
+ useEffect(() => { load(); }, [orgCtx.selectedOrgId]);
1144
1150
 
1145
1151
  // Delete moved to agent detail overview tab with triple confirmation
1146
1152
 
@@ -1149,6 +1155,7 @@ export function AgentsPage({ onSelectAgent }) {
1149
1155
  var _tip = { marginTop: 12, padding: 12, background: 'var(--bg-secondary, #1e293b)', borderRadius: 'var(--radius, 8px)', fontSize: 13 };
1150
1156
 
1151
1157
  return h(Fragment, null,
1158
+ h(orgCtx.Switcher),
1152
1159
  h('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20 } },
1153
1160
  h('div', null, h('h1', { style: { fontSize: 20, fontWeight: 700, display: 'flex', alignItems: 'center' } }, 'Agents', h(HelpButton, { label: 'Agents' },
1154
1161
  h('p', null, 'Your AI workforce. Each agent has its own email identity, personality, skills, permissions, and deployment target.'),
@@ -1,8 +1,11 @@
1
1
  import { h, useState, useEffect, Fragment, useApp, engineCall, showConfirm, buildAgentEmailMap, buildAgentDataMap, resolveAgentEmail, renderAgentBadge, getOrgId } from '../components/utils.js';
2
2
  import { I } from '../components/icons.js';
3
3
  import { HelpButton } from '../components/help-button.js';
4
+ import { useOrgContext } from '../components/org-switcher.js';
4
5
 
5
6
  export function ApprovalsPage() {
7
+ var orgCtx = useOrgContext();
8
+ var effectiveOrgId = orgCtx.selectedOrgId || getOrgId();
6
9
  const { toast } = useApp();
7
10
  const [pending, setPending] = useState([]);
8
11
  const [history, setHistory] = useState([]);
@@ -13,7 +16,7 @@ export function ApprovalsPage() {
13
16
  const load = () => {
14
17
  engineCall('/approvals/pending').then(d => setPending(d.requests || [])).catch(() => {});
15
18
  engineCall('/approvals/history?limit=50').then(d => setHistory(d.requests || [])).catch(() => {});
16
- engineCall('/agents?orgId=' + getOrgId()).then(d => setAgents(d.agents || [])).catch(() => {});
19
+ engineCall('/agents?orgId=' + effectiveOrgId).then(d => setAgents(d.agents || [])).catch(() => {});
17
20
  };
18
21
  useEffect(() => { load(); }, []);
19
22
 
@@ -33,6 +36,7 @@ export function ApprovalsPage() {
33
36
  var _tip = { marginTop: 12, padding: 12, background: 'var(--bg-secondary, #1e293b)', borderRadius: 'var(--radius, 8px)', fontSize: 13 };
34
37
 
35
38
  return h(Fragment, null,
39
+ h(orgCtx.Switcher),
36
40
  h('div', { style: { marginBottom: 20 } },
37
41
  h('h1', { style: { fontSize: 20, fontWeight: 700, display: 'flex', alignItems: 'center' } }, 'Approvals', h(HelpButton, { label: 'Approvals' },
38
42
  h('p', null, 'The human-in-the-loop checkpoint. When agents attempt sensitive actions (based on your permission settings), they pause and wait for your approval here.'),
@@ -2,6 +2,7 @@ import { h, useState, useEffect, Fragment, buildAgentEmailMap, buildAgentDataMap
2
2
  import { I } from '../components/icons.js';
3
3
  import { DetailModal } from '../components/modal.js';
4
4
  import { HelpButton } from '../components/help-button.js';
5
+ import { useOrgContext } from '../components/org-switcher.js';
5
6
 
6
7
  export function SetupChecklist({ onNavigate }) {
7
8
  const [status, setStatus] = useState(null);
@@ -46,6 +47,8 @@ export function SetupChecklist({ onNavigate }) {
46
47
  }
47
48
 
48
49
  export function DashboardPage() {
50
+ var orgCtx = useOrgContext();
51
+ var effectiveOrgId = orgCtx.selectedOrgId || effectiveOrgId;
49
52
  const [stats, setStats] = useState(null);
50
53
  const [agents, setAgents] = useState([]);
51
54
  const [events, setEvents] = useState([]);
@@ -58,9 +61,9 @@ export function DashboardPage() {
58
61
  useEffect(() => {
59
62
  apiCall('/stats').then(setStats).catch(() => {});
60
63
  apiCall('/agents').then(d => setAgents(d.agents || d || [])).catch(() => {});
61
- engineCall('/agents?orgId=' + getOrgId()).then(d => setEngineAgents(d.agents || [])).catch(() => {});
64
+ engineCall('/agents?orgId=' + effectiveOrgId).then(d => setEngineAgents(d.agents || [])).catch(() => {});
62
65
  engineCall('/activity/events?limit=10').then(d => setEvents(d.events || [])).catch(() => {});
63
- }, []);
66
+ }, [effectiveOrgId]);
64
67
 
65
68
  // Merge admin + engine agents; engine agents (appended last) win in the data map
66
69
  var mergedForMap = [].concat(agents, engineAgents);
@@ -73,6 +76,7 @@ export function DashboardPage() {
73
76
  var _tip = { marginTop: 12, padding: 12, background: 'var(--bg-secondary, #1e293b)', borderRadius: 'var(--radius, 8px)', fontSize: 13 };
74
77
 
75
78
  return h(Fragment, null,
79
+ h(orgCtx.Switcher),
76
80
  h(SetupChecklist, { onNavigate: function(pg) { if (navTo) navTo(pg); } }),
77
81
  h('div', { className: 'stat-grid' },
78
82
  h('div', { className: 'stat-card' }, h('div', { className: 'stat-label', style: { display: 'flex', alignItems: 'center' } }, 'Total Agents', h(HelpButton, { label: 'Total Agents' },
@@ -1,6 +1,7 @@
1
1
  import { h, useState, useEffect, useCallback, Fragment, useApp, engineCall, buildAgentEmailMap, resolveAgentEmail, buildAgentDataMap, renderAgentBadge, getOrgId } from '../components/utils.js';
2
2
  import { I } from '../components/icons.js';
3
3
  import { HelpButton } from '../components/help-button.js';
4
+ import { useOrgContext } from '../components/org-switcher.js';
4
5
 
5
6
  // ─── Constants ──────────────────────────────────────────
6
7
 
@@ -93,6 +94,8 @@ function EmptyState(props) {
93
94
  // ─── Main Page ──────────────────────────────────────────
94
95
 
95
96
  export function GuardrailsPage() {
97
+ var orgCtx = useOrgContext();
98
+ var effectiveOrgId = orgCtx.selectedOrgId || getOrgId();
96
99
  var app = useApp();
97
100
  var toast = app.toast;
98
101
  var tab = useState('overview');
@@ -101,7 +104,7 @@ export function GuardrailsPage() {
101
104
  var _ag = useState([]);
102
105
  var agents = _ag[0]; var setAgents = _ag[1];
103
106
  useEffect(function() {
104
- engineCall('/agents?orgId=' + getOrgId()).then(function(d) { setAgents(d.agents || []); }).catch(function() {});
107
+ engineCall('/agents?orgId=' + effectiveOrgId).then(function(d) { setAgents(d.agents || []); }).catch(function() {});
105
108
  }, []);
106
109
 
107
110
  var TABS = [
@@ -164,8 +167,8 @@ function OverviewTab(props) {
164
167
  var load = function() {
165
168
  setLoading(true);
166
169
  Promise.all([
167
- engineCall('/guardrails/interventions?orgId=' + getOrgId() + '&limit=10').catch(function() { return { interventions: [] }; }),
168
- engineCall('/policies?orgId=' + getOrgId()).catch(function() { return { policies: [] }; }),
170
+ engineCall('/guardrails/interventions?orgId=' + effectiveOrgId + '&limit=10').catch(function() { return { interventions: [] }; }),
171
+ engineCall('/policies?orgId=' + effectiveOrgId).catch(function() { return { policies: [] }; }),
169
172
  engineCall('/onboarding/org/default').catch(function() { return { progress: [] }; }),
170
173
  ]).then(function(res) {
171
174
  setInterventions(res[0].interventions || []);
@@ -203,6 +206,7 @@ function OverviewTab(props) {
203
206
  var typeColor = function(t) { return t === 'kill' ? '#ef4444' : t === 'pause' ? '#f59e0b' : t === 'resume' ? '#15803d' : '#0ea5e9'; };
204
207
 
205
208
  return h(Fragment, null,
209
+ h(orgCtx.Switcher),
206
210
  // Quick action bar
207
211
  h('div', { className: 'card', style: { marginBottom: 16 } },
208
212
  h('div', { className: 'card-body', style: { display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' } },
@@ -282,17 +286,17 @@ function PoliciesTab() {
282
286
  var editPolicy = _edit[0]; var setEditPolicy = _edit[1];
283
287
  var _exp = useState(null);
284
288
  var expanded = _exp[0]; var setExpanded = _exp[1];
285
- var _form = useState({ orgId: getOrgId(), name: '', category: 'code_of_conduct', description: '', content: '', priority: 0, enforcement: 'mandatory', appliesTo: ['*'], tags: [], enabled: true });
289
+ var _form = useState({ orgId: effectiveOrgId, name: '', category: 'code_of_conduct', description: '', content: '', priority: 0, enforcement: 'mandatory', appliesTo: ['*'], tags: [], enabled: true });
286
290
  var form = _form[0]; var setForm = _form[1];
287
291
 
288
292
  var load = function() {
289
- engineCall('/policies?orgId=' + getOrgId()).then(function(d) { setPolicies(d.policies || []); }).catch(function() {});
293
+ engineCall('/policies?orgId=' + effectiveOrgId).then(function(d) { setPolicies(d.policies || []); }).catch(function() {});
290
294
  };
291
295
  useEffect(load, []);
292
296
 
293
297
  var openCreate = function() {
294
298
  setEditPolicy(null);
295
- setForm({ orgId: getOrgId(), name: '', category: 'code_of_conduct', description: '', content: '', priority: 0, enforcement: 'mandatory', appliesTo: ['*'], tags: [], enabled: true });
299
+ setForm({ orgId: effectiveOrgId, name: '', category: 'code_of_conduct', description: '', content: '', priority: 0, enforcement: 'mandatory', appliesTo: ['*'], tags: [], enabled: true });
296
300
  setShowModal(true);
297
301
  };
298
302
  var openEdit = function(p) {
@@ -314,7 +318,7 @@ function PoliciesTab() {
314
318
  .catch(function(e) { toast(e.message, 'error'); });
315
319
  };
316
320
  var applyDefaults = function() {
317
- engineCall('/policies/templates/apply', { method: 'POST', body: JSON.stringify({ orgId: getOrgId(), createdBy: 'admin' }) })
321
+ engineCall('/policies/templates/apply', { method: 'POST', body: JSON.stringify({ orgId: effectiveOrgId, createdBy: 'admin' }) })
318
322
  .then(function(d) { toast('Applied ' + (d.policies ? d.policies.length : 0) + ' default templates', 'success'); load(); })
319
323
  .catch(function(e) { toast(e.message, 'error'); });
320
324
  };
@@ -451,7 +455,7 @@ function OnboardingTab(props) {
451
455
 
452
456
  var initiate = function() {
453
457
  if (!initAgentId) { toast('Enter an agent ID', 'error'); return; }
454
- engineCall('/onboarding/initiate/' + initAgentId, { method: 'POST', body: JSON.stringify({ orgId: getOrgId() }) })
458
+ engineCall('/onboarding/initiate/' + initAgentId, { method: 'POST', body: JSON.stringify({ orgId: effectiveOrgId }) })
455
459
  .then(function() { toast('Onboarding initiated', 'success'); setInitAgentId(''); load(); })
456
460
  .catch(function(e) { toast(e.message, 'error'); });
457
461
  };
@@ -461,7 +465,7 @@ function OnboardingTab(props) {
461
465
  .catch(function(e) { toast(e.message, 'error'); });
462
466
  };
463
467
  var checkChanges = function() {
464
- engineCall('/onboarding/check-changes', { method: 'POST', body: JSON.stringify({ orgId: getOrgId() }) })
468
+ engineCall('/onboarding/check-changes', { method: 'POST', body: JSON.stringify({ orgId: effectiveOrgId }) })
465
469
  .then(function(d) {
466
470
  var stale = d.staleAgents || [];
467
471
  if (stale.length === 0) { toast('All agents up to date', 'success'); }
@@ -555,7 +559,7 @@ function MemoryTab(props) {
555
559
  var showCreate = _show[0]; var setShowCreate = _show[1];
556
560
  var _exp = useState(null);
557
561
  var expanded = _exp[0]; var setExpanded = _exp[1];
558
- var _form = useState({ agentId: '', orgId: getOrgId(), category: 'org_knowledge', title: '', content: '', source: 'admin', importance: 'normal', tags: [] });
562
+ var _form = useState({ agentId: '', orgId: effectiveOrgId, category: 'org_knowledge', title: '', content: '', source: 'admin', importance: 'normal', tags: [] });
559
563
  var form = _form[0]; var setForm = _form[1];
560
564
 
561
565
  var loadMemories = function(aid) {
@@ -762,13 +766,13 @@ function RulesTab(props) {
762
766
  var _showAnomaly = useState(false);
763
767
  var showAnomalyModal = _showAnomaly[0]; var setShowAnomalyModal = _showAnomaly[1];
764
768
  var _form = useState({
765
- orgId: getOrgId(), name: '', description: '', category: 'anomaly', ruleType: 'threshold',
769
+ orgId: effectiveOrgId, name: '', description: '', category: 'anomaly', ruleType: 'threshold',
766
770
  conditions: { threshold: 10, windowMinutes: 60 },
767
771
  action: 'alert', severity: 'medium', cooldownMinutes: 15, enabled: true
768
772
  });
769
773
  var form = _form[0]; var setForm = _form[1];
770
774
  var _anomalyForm = useState({
771
- orgId: getOrgId(), name: '', ruleType: 'error_rate',
775
+ orgId: effectiveOrgId, name: '', ruleType: 'error_rate',
772
776
  config: { maxErrorsPerHour: 50, windowMinutes: 60 }, action: 'pause', enabled: true
773
777
  });
774
778
  var anomalyForm = _anomalyForm[0]; var setAnomalyForm = _anomalyForm[1];
@@ -777,9 +781,9 @@ function RulesTab(props) {
777
781
 
778
782
  var load = function() {
779
783
  Promise.all([
780
- engineCall('/guardrails/rules?orgId=' + getOrgId()).catch(function() { return { rules: [] }; }),
781
- engineCall('/anomaly-rules?orgId=' + getOrgId()).catch(function() { return { rules: [] }; }),
782
- engineCall('/guardrails/interventions?orgId=' + getOrgId() + '&limit=50').catch(function() { return { interventions: [] }; }),
784
+ engineCall('/guardrails/rules?orgId=' + effectiveOrgId).catch(function() { return { rules: [] }; }),
785
+ engineCall('/anomaly-rules?orgId=' + effectiveOrgId).catch(function() { return { rules: [] }; }),
786
+ engineCall('/guardrails/interventions?orgId=' + effectiveOrgId + '&limit=50').catch(function() { return { interventions: [] }; }),
783
787
  ]).then(function(res) {
784
788
  setRules(res[0].rules || []);
785
789
  setAnomalyRules(res[1].rules || []);
@@ -791,7 +795,7 @@ function RulesTab(props) {
791
795
  // Guardrail rules CRUD
792
796
  var openCreateRule = function() {
793
797
  setEditRule(null);
794
- setForm({ orgId: getOrgId(), name: '', description: '', category: 'anomaly', ruleType: 'threshold', conditions: { threshold: 10, windowMinutes: 60 }, action: 'alert', severity: 'medium', cooldownMinutes: 15, enabled: true });
798
+ setForm({ orgId: effectiveOrgId, name: '', description: '', category: 'anomaly', ruleType: 'threshold', conditions: { threshold: 10, windowMinutes: 60 }, action: 'alert', severity: 'medium', cooldownMinutes: 15, enabled: true });
795
799
  setShowModal(true);
796
800
  };
797
801
  var openEditRule = function(r) {
@@ -1,8 +1,11 @@
1
1
  import { h, useState, useEffect, Fragment, useApp, engineCall, buildAgentEmailMap, buildAgentDataMap, resolveAgentEmail, renderAgentBadge, getOrgId } from '../components/utils.js';
2
2
  import { I } from '../components/icons.js';
3
3
  import { HelpButton } from '../components/help-button.js';
4
+ import { useOrgContext } from '../components/org-switcher.js';
4
5
 
5
6
  export function JournalPage() {
7
+ var orgCtx = useOrgContext();
8
+ var effectiveOrgId = orgCtx.selectedOrgId || getOrgId();
6
9
  const { toast } = useApp();
7
10
  const [entries, setEntries] = useState([]);
8
11
  const [total, setTotal] = useState(0);
@@ -11,9 +14,9 @@ export function JournalPage() {
11
14
  const [agents, setAgents] = useState([]);
12
15
 
13
16
  const load = () => {
14
- engineCall('/journal?orgId=' + getOrgId() + '&limit=50').then(d => { setEntries(d.entries || []); setTotal(d.total || 0); }).catch(() => {});
17
+ engineCall('/journal?orgId=' + effectiveOrgId + '&limit=50').then(d => { setEntries(d.entries || []); setTotal(d.total || 0); }).catch(() => {});
15
18
  engineCall('/journal/stats/default').then(d => setStats(d)).catch(() => {});
16
- engineCall('/agents?orgId=' + getOrgId()).then(d => setAgents(d.agents || [])).catch(() => {});
19
+ engineCall('/agents?orgId=' + effectiveOrgId).then(d => setAgents(d.agents || [])).catch(() => {});
17
20
  };
18
21
  useEffect(load, []);
19
22
 
@@ -29,6 +32,7 @@ export function JournalPage() {
29
32
  var _tip = { marginTop: 12, padding: 12, background: 'var(--bg-secondary, #1e293b)', borderRadius: 'var(--radius, 8px)', fontSize: 13 };
30
33
 
31
34
  return h('div', { className: 'page-inner' },
35
+ h(orgCtx.Switcher),
32
36
  h('div', { className: 'page-header' }, h('h1', { style: { display: 'flex', alignItems: 'center' } }, 'Action Journal', h(HelpButton, { label: 'Action Journal' },
33
37
  h('p', null, 'A tamper-proof log of every action agents have taken. Think of it as an audit trail — every tool call, every side effect, recorded with full context.'),
34
38
  h('h4', { style: _h4 }, 'Why it matters'),
@@ -2,9 +2,11 @@ import { h, useState, useEffect, useCallback, Fragment, useApp, engineCall, buil
2
2
  import { I } from '../components/icons.js';
3
3
  import { Modal } from '../components/modal.js';
4
4
  import { HelpButton } from '../components/help-button.js';
5
+ import { useOrgContext } from '../components/org-switcher.js';
5
6
 
6
7
  export function KnowledgeContributionsPage() {
7
8
  var { toast } = useApp();
9
+ var orgCtx = useOrgContext();
8
10
  var [tab, setTab] = useState('bases');
9
11
  var [bases, setBases] = useState([]);
10
12
  var [roles, setRoles] = useState([]);
@@ -39,14 +41,17 @@ export function KnowledgeContributionsPage() {
39
41
  var [searchDays, setSearchDays] = useState(7);
40
42
  var [searchAgentFilter, setSearchAgentFilter] = useState('');
41
43
 
44
+ // Effective org ID: uses client org if selected, else default
45
+ var effectiveOrgId = orgCtx.selectedOrgId || effectiveOrgId;
46
+
42
47
  var loadBases = useCallback(function() {
43
48
  Promise.all([
44
- engineCall('/knowledge-contribution/bases?orgId=' + getOrgId()).catch(function() { return { bases: [] }; }),
49
+ engineCall('/knowledge-contribution/bases?orgId=' + effectiveOrgId).catch(function() { return { bases: [] }; }),
45
50
  engineCall('/knowledge-bases').catch(function() { return { knowledgeBases: [] }; })
46
51
  ]).then(function(results) {
47
52
  var contribBases = results[0].bases || [];
48
53
  var mainBases = (results[1].knowledgeBases || []).map(function(kb) {
49
- return { id: kb.id, orgId: getOrgId(), name: kb.name, description: kb.description, role: 'general', categories: [], contributorCount: 0, entryCount: kb.stats ? kb.stats.documentCount || 0 : 0, createdAt: kb.createdAt, updatedAt: kb.updatedAt, _source: 'main' };
54
+ return { id: kb.id, orgId: effectiveOrgId, name: kb.name, description: kb.description, role: 'general', categories: [], contributorCount: 0, entryCount: kb.stats ? kb.stats.documentCount || 0 : 0, createdAt: kb.createdAt, updatedAt: kb.updatedAt, _source: 'main' };
50
55
  });
51
56
  // Merge: contribution bases first, then main bases not already in contribution
52
57
  var ids = {};
@@ -63,19 +68,19 @@ export function KnowledgeContributionsPage() {
63
68
  }, []);
64
69
 
65
70
  var loadStats = useCallback(function() {
66
- engineCall('/knowledge-contribution/stats?orgId=' + getOrgId())
71
+ engineCall('/knowledge-contribution/stats?orgId=' + effectiveOrgId)
67
72
  .then(function(d) { setStats(d || {}); })
68
73
  .catch(function() {});
69
74
  }, []);
70
75
 
71
76
  var loadContributions = useCallback(function() {
72
- engineCall('/knowledge-contribution/contributions?orgId=' + getOrgId())
77
+ engineCall('/knowledge-contribution/contributions?orgId=' + effectiveOrgId)
73
78
  .then(function(d) { setContributions(d.contributions || d.cycles || []); })
74
79
  .catch(function() {});
75
80
  }, []);
76
81
 
77
82
  var loadSchedules = useCallback(function() {
78
- engineCall('/knowledge-contribution/schedules?orgId=' + getOrgId())
83
+ engineCall('/knowledge-contribution/schedules?orgId=' + effectiveOrgId)
79
84
  .then(function(d) { setSchedules(d.schedules || []); })
80
85
  .catch(function() {});
81
86
  }, []);
@@ -86,10 +91,10 @@ export function KnowledgeContributionsPage() {
86
91
  loadStats();
87
92
  loadContributions();
88
93
  loadSchedules();
89
- engineCall('/agents?orgId=' + getOrgId()).then(function(d) { setAgents(d.agents || []); }).catch(function() {});
94
+ engineCall('/agents?orgId=' + effectiveOrgId).then(function(d) { setAgents(d.agents || []); }).catch(function() {});
90
95
  }, [loadBases, loadRoles, loadStats, loadContributions, loadSchedules]);
91
96
 
92
- useEffect(function() { load(); }, [load]);
97
+ useEffect(function() { load(); }, [load, effectiveOrgId]);
93
98
 
94
99
  var loadBaseEntries = useCallback(function(baseId) {
95
100
  var params = new URLSearchParams();
@@ -110,7 +115,7 @@ export function KnowledgeContributionsPage() {
110
115
  try {
111
116
  await engineCall('/knowledge-contribution/bases', {
112
117
  method: 'POST',
113
- body: JSON.stringify({ name: baseForm.name, description: baseForm.description, role: baseForm.role, orgId: getOrgId() })
118
+ body: JSON.stringify({ name: baseForm.name, description: baseForm.description, role: baseForm.role, orgId: effectiveOrgId })
114
119
  });
115
120
  toast('Knowledge base created', 'success');
116
121
  setShowCreateBase(false);
@@ -161,7 +166,7 @@ export function KnowledgeContributionsPage() {
161
166
  try {
162
167
  await engineCall('/knowledge-contribution/contribute/' + triggerAgent, {
163
168
  method: 'POST',
164
- body: JSON.stringify({ targetBaseId: triggerBase || undefined, orgId: getOrgId() })
169
+ body: JSON.stringify({ targetBaseId: triggerBase || undefined, orgId: effectiveOrgId })
165
170
  });
166
171
  toast('Contribution triggered', 'success');
167
172
  setShowTrigger(false);
@@ -182,7 +187,7 @@ export function KnowledgeContributionsPage() {
182
187
  frequency: scheduleForm.frequency,
183
188
  dayOfWeek: scheduleForm.dayOfWeek,
184
189
  minConfidence: parseFloat(scheduleForm.minConfidence) || 0.7,
185
- orgId: getOrgId()
190
+ orgId: effectiveOrgId
186
191
  })
187
192
  });
188
193
  toast('Schedule created', 'success');
@@ -1375,6 +1380,9 @@ export function KnowledgeContributionsPage() {
1375
1380
  };
1376
1381
 
1377
1382
  return h(Fragment, null,
1383
+ // Org context switcher
1384
+ h(orgCtx.Switcher),
1385
+
1378
1386
  // Header
1379
1387
  h('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20 } },
1380
1388
  h('div', null,